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::{AtomicBool, 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    /// Set when the server says it does not know this session. The id is sent on every later call, so
297    /// the connection is dropped rather than reused (`#568`); nothing is half-read over HTTP, which is
298    /// why this is a flag and not the pipe's poison.
299    expired: Arc<AtomicBool>,
300}
301
302impl Drop for Pipe {
303    fn drop(&mut self) {
304        // Dropping a `Child` leaves it running, so a connection that ends — a timeout, a crash, the
305        // agent exiting — has to say so. This is the only place a server process dies.
306        //
307        // `#418`: killing the *direct* child was not enough. A server started through `npx` or
308        // `sh -c` is a grandchild, it inherits the stdout pipe, and it outlives its parent — so the
309        // reader thread stayed blocked on a pipe nobody would ever write to again, for the life of
310        // the process. The server is started in its own process group, so the group and the tree go
311        // together, and the direct child is still killed for the group-less (non-unix) path.
312        #[cfg(unix)]
313        crate::tools::pgroup::kill_now(self.child.id());
314        let _ = self.child.kill();
315        let _ = self.child.wait();
316    }
317}
318
319/// The longest line a server may send. A JSON-RPC message is a line, and a tool result can be
320/// large — but not gigabytes: `BufReader::lines()` allocated whatever arrived with no newline in
321/// sight, so a server that never sent one could exhaust memory before any cap was consulted
322/// (`#418`). Past this the line is discarded and reported, not buffered.
323const MAX_LINE: usize = 8 * 1024 * 1024;
324
325/// How many parsed messages may wait between the reader thread and the request that reads them.
326/// Unbounded was the default, which let a chatty server queue without limit; a full queue now stops
327/// the reader, which stops the server on its next write — back-pressure instead of growth.
328const LINE_QUEUE: usize = 64;
329
330/// One line, or the fact that it was too long to keep.
331enum Line {
332    Text(String),
333    TooLong(usize),
334}
335
336/// Read one `\n`-terminated line without ever holding more than `max` bytes of it.
337///
338/// `read_until` and `lines()` both grow a `Vec` to whatever the writer sent; this consumes the
339/// buffer as it goes and keeps counting after the cap, so a server that writes a gigabyte without a
340/// newline costs a counter rather than the rest of the machine's memory.
341fn read_line_capped<R: BufRead>(reader: &mut R, max: usize) -> std::io::Result<Option<Line>> {
342    let mut kept: Vec<u8> = Vec::new();
343    let mut seen = 0usize;
344    let mut over = false;
345    loop {
346        let avail = reader.fill_buf()?;
347        if avail.is_empty() {
348            if seen == 0 {
349                return Ok(None);
350            }
351            break;
352        }
353        let newline = avail.iter().position(|b| *b == b'\n');
354        let take = newline.unwrap_or(avail.len());
355        seen += take;
356        if !over {
357            if kept.len() + take > max {
358                over = true;
359                kept.clear();
360            } else {
361                kept.extend_from_slice(&avail[..take]);
362            }
363        }
364        match newline {
365            Some(_) => {
366                reader.consume(take + 1);
367                break;
368            }
369            None => reader.consume(take),
370        }
371    }
372    if over {
373        return Ok(Some(Line::TooLong(seen)));
374    }
375    Ok(Some(Line::Text(
376        String::from_utf8_lossy(&kept).into_owned(),
377    )))
378}
379
380/// How long a wait may run before it looks at the cancellation flag again. A tool call is a blocking
381/// read on a pipe, so this is the granularity at which a cancelled run stops waiting for one.
382const CANCEL_TICK: Duration = Duration::from_millis(100);
383
384/// One MCP server, shared by the tools it offers.
385pub struct Server {
386    spec: Spec,
387    plugin_dir: PathBuf,
388    workspace: PathBuf,
389    timeout: Duration,
390    /// Where a `token_env` variable is looked up when the process environment does not set it —
391    /// the `.env` values the config loaded (`#516`). Held here because the token is read at
392    /// connect time, which is after the registry that built this server is gone.
393    secrets: Secrets,
394    next_id: AtomicI64,
395    state: Mutex<Option<Conn>>,
396    /// What the server answered `initialize` with — `protocolVersion`, and its own name and
397    /// version. Kept because `eclipse mcp test` is asked to *prove* a server works, and "it listed
398    /// three tools" says nothing about which protocol it speaks (`#352`).
399    handshake: Mutex<Option<Value>>,
400    stderr: Arc<Mutex<String>>,
401}
402
403impl std::fmt::Debug for Server {
404    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405        f.debug_struct("mcp::Server")
406            .field("name", &self.spec.name)
407            .field("transport", &self.spec.transport.as_str())
408            .field("command", &self.spec.command)
409            .field("url", &self.spec.url)
410            .finish()
411    }
412}
413
414impl Server {
415    /// Start a server and ask it what it can do. Blocking on purpose: this runs while a registry is
416    /// being built, outside any turn, and a manifest that names a broken server should say so at
417    /// startup rather than at the first tool call.
418    pub fn start(
419        spec: &Spec,
420        plugin_dir: &Path,
421        workspace: &Path,
422        default_timeout: Duration,
423        secrets: &Secrets,
424    ) -> Result<(Arc<Self>, Vec<RemoteTool>), String> {
425        // The server's own `timeout_secs` wins; `[plugins] mcp_timeout_secs` is the machine-wide
426        // default for the ones that do not say. Both are clamped the same way.
427        let timeout = match spec.timeout_secs {
428            Some(secs) => crate::plugins::clamp_timeout(Some(secs)),
429            None => default_timeout,
430        };
431        let server = Arc::new(Self {
432            spec: spec.clone(),
433            plugin_dir: plugin_dir.to_path_buf(),
434            workspace: workspace.to_path_buf(),
435            timeout,
436            secrets: secrets.clone(),
437            next_id: AtomicI64::new(1),
438            state: Mutex::new(None),
439            handshake: Mutex::new(None),
440            stderr: Arc::new(Mutex::new(String::new())),
441        });
442        let tools = server.list_tools()?;
443        Ok((server, tools))
444    }
445
446    pub fn name(&self) -> &str {
447        &self.spec.name
448    }
449
450    pub fn prefix(&self) -> &str {
451        &self.spec.prefix
452    }
453
454    /// The `initialize` result, if the handshake got that far.
455    pub fn handshake(&self) -> Option<Value> {
456        self.handshake
457            .lock()
458            .unwrap_or_else(|e| e.into_inner())
459            .clone()
460    }
461
462    /// Remember the handshake for `mcp test`. First answer wins: a server is started once per
463    /// process, so nothing legitimately writes a second one.
464    fn keep_handshake(&self, result: &Value) {
465        let mut slot = self.handshake.lock().unwrap_or_else(|e| e.into_inner());
466        if slot.is_none() {
467            *slot = Some(result.clone());
468        }
469    }
470
471    pub fn override_builtin(&self) -> bool {
472        self.spec.override_builtin
473    }
474
475    /// The policy a remote tool gets: its own override, else the server's.
476    pub fn policy_for(&self, remote: &str) -> Policy {
477        self.spec
478            .policies
479            .get(remote)
480            .copied()
481            .unwrap_or(self.spec.policy)
482    }
483
484    /// `tools/list`, following `nextCursor` because a server with more than one page of tools is
485    /// not rare (a filesystem server can offer a dozen) and stopping at page one would silently
486    /// hide the rest.
487    fn list_tools(&self) -> Result<Vec<RemoteTool>, String> {
488        let mut out = Vec::new();
489        let mut cursor: Option<String> = None;
490        for _ in 0..16 {
491            let params = match &cursor {
492                Some(c) => json!({ "cursor": c }),
493                None => json!({}),
494            };
495            // Listing happens before a run exists: no flag to honour.
496            let result = self.request("tools/list", params, &crate::cancel::Cancel::new())?;
497            let page: Vec<RemoteTool> =
498                serde_json::from_value(result.get("tools").cloned().unwrap_or_else(|| json!([])))
499                    .map_err(|e| {
500                    format!("`tools/list` answered with tools this build cannot read: {e}")
501                })?;
502            out.extend(page);
503            cursor = result
504                .get("nextCursor")
505                .and_then(Value::as_str)
506                .map(str::to_string)
507                .filter(|c| !c.is_empty());
508            if cursor.is_none() {
509                break;
510            }
511        }
512        Ok(out)
513    }
514
515    /// `tools/call`, from a thread that is allowed to block.
516    pub fn call_tool(&self, remote: &str, args: &Value) -> Result<String, String> {
517        self.call_tool_unless(remote, args, &crate::cancel::Cancel::new())
518    }
519
520    /// [`call_tool`](Self::call_tool) with a run's cancellation flag.
521    ///
522    /// A tool call is not interruptible — it is a blocking read on a pipe — but *waiting* for it is.
523    /// When the run is cancelled the answer has nowhere to go, so the wait stops, the connection is
524    /// dropped (which kills the server) and the caller gets the reason.
525    pub fn call_tool_unless(
526        &self,
527        remote: &str,
528        args: &Value,
529        cancel: &crate::cancel::Cancel,
530    ) -> Result<String, String> {
531        let result = self.request(
532            "tools/call",
533            json!({ "name": remote, "arguments": args }),
534            cancel,
535        )?;
536        let text = content_text(&result);
537        if result
538            .get("isError")
539            .and_then(Value::as_bool)
540            .unwrap_or(false)
541        {
542            // The server said the *tool* failed. That is a tool error, not a transport error, and
543            // the model reads it as one.
544            return Err(if text.is_empty() {
545                "the tool reported a failure without a message".to_string()
546            } else {
547                text
548            });
549        }
550        Ok(text)
551    }
552
553    fn request(
554        &self,
555        method: &str,
556        params: Value,
557        cancel: &crate::cancel::Cancel,
558    ) -> Result<Value, String> {
559        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
560        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
561        self.ensure(&mut guard)?;
562        let message = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
563        let (outcome, poison) = match guard.as_mut().expect("ensure left a connection") {
564            Conn::Pipe(pipe) => self.exchange_pipe(pipe, id, method, &message, cancel),
565            // An HTTP exchange leaves nothing half-read, so there is no pipe to poison (`#502`) —
566            // but a session the server has forgotten is not reusable either, and that is what the
567            // second half of the answer says (`#568`).
568            Conn::Http(http) => self.exchange_http(http, id, method, &message, cancel),
569        };
570        if poison {
571            // Dropping the connection kills the process; the answer to this id may still be on
572            // the pipe and every later request would read it.
573            *guard = None;
574        }
575        outcome
576    }
577
578    /// Write one message to the server's stdin without letting a dead server kill the process.
579    ///
580    /// The CLI sets `SIGPIPE` to `SIG_DFL` on purpose (so `eclipse … | head` exits quietly instead
581    /// of panicking on a closed stdout). The cost is that a write to a pipe whose reader has gone
582    /// is a *signal*, not an `EPIPE` error — a server that exits before we finish writing to it
583    /// takes the whole agent down with it, silently. That is now the ordinary case, not a corner:
584    /// `eclipse mcp list` starts every server it lists, so one broken entry killed the command
585    /// that was supposed to report it.
586    ///
587    /// Blocking the signal with `pthread_sigmask` does **not** fix this: a signal is delivered to
588    /// any thread that has it unblocked, and the runtime has reader threads by the time a server is
589    /// started. So the disposition is switched to `SIG_IGN` for the duration of the write — which
590    /// discards the signal instead of queueing it — and put back afterwards. Ignored signals are
591    /// dropped rather than left pending, so nothing is delivered late. The lock is there because
592    /// swapping a process-wide disposition twice is not something two writers may interleave.
593    fn write_stdin(
594        &self,
595        stdin: &mut std::process::ChildStdin,
596        message: &str,
597    ) -> std::io::Result<()> {
598        #[cfg(unix)]
599        // SAFETY: `signal` with `SIG_IGN`, a previously returned handler, or `SIG_DFL` is sound for
600        // any disposition; the lock keeps the swap from interleaving with another writer's.
601        unsafe {
602            static SIGPIPE_SWAP: std::sync::Mutex<()> = std::sync::Mutex::new(());
603            let _guard = SIGPIPE_SWAP.lock().unwrap_or_else(|e| e.into_inner());
604            let previous = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
605            let result = writeln!(stdin, "{message}").and_then(|_| stdin.flush());
606            libc::signal(libc::SIGPIPE, previous);
607            result
608        }
609        #[cfg(not(unix))]
610        {
611            writeln!(stdin, "{message}").and_then(|_| stdin.flush())
612        }
613    }
614
615    /// One exchange on a pipe, and whether it poisoned it.
616    fn exchange_pipe(
617        &self,
618        pipe: &mut Pipe,
619        id: i64,
620        method: &str,
621        message: &Value,
622        cancel: &crate::cancel::Cancel,
623    ) -> (Result<Value, String>, bool) {
624        if let Err(e) = self.write_stdin(&mut pipe.stdin, &message.to_string()) {
625            return (
626                Err(format!(
627                    "could not send `{method}`: {e}{}",
628                    self.stderr_tail_soon()
629                )),
630                true,
631            );
632        }
633        let deadline = Instant::now() + self.timeout;
634        loop {
635            if cancel.is_cancelled() {
636                return (
637                    Err(format!(
638                        "`{method}` was cancelled before the server answered; it has been stopped"
639                    )),
640                    true,
641                );
642            }
643            let left = deadline
644                .saturating_duration_since(Instant::now())
645                .min(CANCEL_TICK);
646            match pipe.rx.recv_timeout(left) {
647                Ok(value) => match answer_to(&value, id, method) {
648                    Answer::NotMine => continue,
649                    Answer::Unparsable(why) => {
650                        return (
651                            Err(format!("the server wrote a line that is not JSON: {why}")),
652                            true,
653                        )
654                    }
655                    Answer::Value(result) => return (Ok(result), false),
656                    Answer::Failed(why) => return (Err(why), false),
657                },
658                Err(RecvTimeoutError::Timeout) => {
659                    // A short tick, so a cancel is noticed while waiting. Only the real deadline is
660                    // the server's failure.
661                    if Instant::now() < deadline {
662                        continue;
663                    }
664                    return (
665                        Err(format!(
666                            "the server did not answer `{method}` within {}s; it has been stopped \
667                             and will be started again on the next call",
668                            self.timeout.as_secs()
669                        )),
670                        true,
671                    );
672                }
673                Err(RecvTimeoutError::Disconnected) => {
674                    return (
675                        Err(format!(
676                            "the server exited while `{method}` was in flight{}",
677                            self.stderr_tail()
678                        )),
679                        true,
680                    )
681                }
682            }
683        }
684    }
685
686    /// One exchange over Streamable HTTP (`#502`).
687    ///
688    /// The message is posted as the whole body; the answer is either a JSON body or an event
689    /// stream, and both are parsed here so `request` does not have to care which arrived.
690    fn exchange_http(
691        &self,
692        http: &mut Http,
693        id: i64,
694        method: &str,
695        message: &Value,
696        cancel: &crate::cancel::Cancel,
697    ) -> (Result<Value, String>, bool) {
698        let reply = match self.post(http, message, Some(id), cancel) {
699            Ok(reply) => reply,
700            Err(message) => return (Err(message), http.expired.load(Ordering::Relaxed)),
701        };
702        let outcome = match answer_to(&reply.value, id, method) {
703            Answer::Value(result) => Ok(result),
704            Answer::Failed(why) => Err(why),
705            Answer::Unparsable(why) => Err(format!("the server answered `{method}` with {why}")),
706            // A server that answers a request with a notification and nothing else has not
707            // answered it. Say that rather than looping for an answer that is not coming.
708            Answer::NotMine => Err(format!(
709                "`{method}` was answered with a message for another id; this build speaks one \
710                 request per post"
711            )),
712        };
713        (outcome, http.expired.load(Ordering::Relaxed))
714    }
715
716    /// A connection, or a new one: a server that died (crashed, was killed) is replaced here, which
717    /// is what makes "crash restarts on next call" true without any supervision thread.
718    fn ensure(&self, slot: &mut Option<Conn>) -> Result<(), String> {
719        let alive = match slot.as_mut() {
720            // A process that exited — crash, kill, `sh -c` that never started the real server — is
721            // replaced here, which is what makes "a crash costs one call" true without a supervisor.
722            Some(Conn::Pipe(pipe)) => matches!(pipe.child.try_wait(), Ok(None)),
723            // An HTTP session has no process to watch: whether it still works is what the next
724            // post finds out (`#502`).
725            Some(Conn::Http(_)) => true,
726            None => false,
727        };
728        if !alive {
729            *slot = None;
730        }
731        if slot.is_none() {
732            *slot = Some(self.connect()?);
733        }
734        Ok(())
735    }
736
737    /// Open the connection the entry asks for — a process, or an HTTP session — and say hello on
738    /// it. A connection is only published once it has answered `initialize`.
739    fn connect(&self) -> Result<Conn, String> {
740        self.spec.validate()?;
741        match self.spec.transport {
742            Transport::Stdio => Ok(Conn::Pipe(self.start_pipe()?)),
743            Transport::Http => Ok(Conn::Http(self.start_http()?)),
744        }
745    }
746
747    /// The Streamable HTTP handshake (`#502`): `initialize`, keep the session id it hands out, then
748    /// `notifications/initialized` — carried *with* that id, because a server that issued one
749    /// rejects the next post without it.
750    fn start_http(&self) -> Result<Http, String> {
751        let url = self
752            .spec
753            .url
754            .as_deref()
755            .map(str::trim)
756            .filter(|u| !u.is_empty())
757            .ok_or("`transport = \"http\"` with no `url` to post to")?
758            .to_string();
759        let token = self.spec.token(&self.secrets)?;
760        let client = reqwest::Client::builder()
761            .user_agent(concat!("eclipse/", env!("CARGO_PKG_VERSION")))
762            .build()
763            .map_err(|e| format!("could not build an HTTP client: {e}"))?;
764        let mut http = Http {
765            client,
766            url,
767            session: None,
768            token,
769            expired: Arc::new(AtomicBool::new(false)),
770        };
771        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
772        let init = json!({
773            "jsonrpc": "2.0",
774            "id": id,
775            "method": "initialize",
776            "params": {
777                "protocolVersion": PROTOCOL,
778                "capabilities": {},
779                "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
780            }
781        });
782        let reply = self.post(&mut http, &init, Some(id), &crate::cancel::Cancel::new())?;
783        // Before anything else: a server that handed out a session id wants it on every later
784        // post, the notification included.
785        if let Some(session) = reply.session {
786            http.session = Some(session);
787        }
788        if let Some(err) = reply.value.get("error") {
789            return Err(format!(
790                "`initialize` was refused: {}",
791                err.get("message")
792                    .and_then(Value::as_str)
793                    .unwrap_or("no message")
794            ));
795        }
796        match answer_to(&reply.value, id, "initialize") {
797            Answer::Value(result) => {
798                if result
799                    .get("protocolVersion")
800                    .and_then(Value::as_str)
801                    .is_none()
802                {
803                    return Err("`initialize` answered without a protocolVersion".into());
804                }
805                self.keep_handshake(&result);
806            }
807            Answer::Failed(why) => return Err(why),
808            Answer::Unparsable(why) => {
809                return Err(format!(
810                    "`initialize` was answered with a body this build cannot read: {why}"
811                ))
812            }
813            Answer::NotMine => {
814                return Err("`initialize` was answered with a message for another id".into())
815            }
816        }
817        let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
818        self.post(&mut http, &ready, None, &crate::cancel::Cancel::new())?;
819        Ok(http)
820    }
821
822    /// One `POST` carrying `message`, and whatever came back (`#502`).
823    ///
824    /// The exchange runs on a runtime of its own in a thread of its own. This module is synchronous
825    /// by design — a pipe has no other option — so the async client is confined to the one place
826    /// that needs it instead of leaking a runtime requirement into every caller. The calling thread
827    /// waits on a channel with the same tick the pipe uses, so a cancelled run stops waiting here
828    /// exactly as it stops there.
829    fn post(
830        &self,
831        http: &mut Http,
832        message: &Value,
833        id: Option<i64>,
834        cancel: &crate::cancel::Cancel,
835    ) -> Result<Reply, String> {
836        let exchange = Exchange {
837            client: http.client.clone(),
838            url: http.url.clone(),
839            session: http.session.clone(),
840            token: http.token.clone(),
841            expired: http.expired.clone(),
842        };
843        let body = message.clone();
844        let timeout = self.timeout;
845        let (tx, rx) = mpsc::channel::<Result<Reply, String>>();
846        std::thread::spawn(move || {
847            let _ = tx.send(over_http(exchange, body, id, timeout));
848        });
849        // The runtime enforces `timeout` on the request itself; this is the ceiling for a thread
850        // that never gets that far, so a hung connect is still a bounded wait.
851        let deadline = Instant::now() + timeout + Duration::from_secs(2);
852        loop {
853            if cancel.is_cancelled() {
854                return Err("the request was cancelled before the server answered".to_string());
855            }
856            let left = deadline
857                .saturating_duration_since(Instant::now())
858                .min(CANCEL_TICK);
859            match rx.recv_timeout(left) {
860                Ok(outcome) => return outcome,
861                Err(RecvTimeoutError::Timeout) => {
862                    if Instant::now() < deadline {
863                        continue;
864                    }
865                    return Err(format!(
866                        "the server did not answer within {}s",
867                        timeout.as_secs()
868                    ));
869                }
870                Err(RecvTimeoutError::Disconnected) => {
871                    return Err("the HTTP exchange ended without an answer".to_string())
872                }
873            }
874        }
875    }
876
877    /// Start the process and say hello to it. The handshake lives here rather than in `request`
878    /// because `request` holds the state mutex and taking it again from inside `ensure` would
879    /// deadlock (std mutexes are not reentrant).
880    fn start_pipe(&self) -> Result<Pipe, String> {
881        let mut cmd = Command::new(&self.spec.command);
882        cmd.args(&self.spec.args)
883            .current_dir(self.cwd())
884            .env_clear()
885            .stdin(Stdio::piped())
886            .stdout(Stdio::piped())
887            .stderr(Stdio::piped());
888        for key in crate::plugins::INHERITED_ENV {
889            if let Ok(v) = std::env::var(key) {
890                cmd.env(key, v);
891            }
892        }
893        for key in &self.spec.env {
894            if let Ok(v) = std::env::var(key) {
895                cmd.env(key, v);
896            }
897        }
898        cmd.env("ECLIPSE_PLUGIN_DIR", &self.plugin_dir)
899            .env("ECLIPSE_WORKSPACE", &self.workspace);
900        // `#418`: its own process group, so `Conn::drop` can take the whole tree down. Without it a
901        // server started through `npx` leaves a grandchild holding the pipe.
902        #[cfg(unix)]
903        cmd.process_group(0);
904        let mut child = cmd
905            .spawn()
906            .map_err(|e| format!("could not start `{}`: {e}", self.spec.command))?;
907        let stdin = child.stdin.take().ok_or("no stdin on the server process")?;
908        let stdout = child
909            .stdout
910            .take()
911            .ok_or("no stdout on the server process")?;
912        // A server's stderr is its log. Reading it on a thread keeps a chatty server from filling the
913        // pipe and blocking on its own writes, and keeps the tail for the error message when
914        // something goes wrong.
915        if let Some(mut err) = child.stderr.take() {
916            let keep = Arc::clone(&self.stderr);
917            std::thread::spawn(move || {
918                let mut buf = [0u8; 1024];
919                loop {
920                    match std::io::Read::read(&mut err, &mut buf) {
921                        Ok(0) | Err(_) => break,
922                        Ok(n) => {
923                            let text = String::from_utf8_lossy(&buf[..n]).into_owned();
924                            let mut slot = keep.lock().unwrap_or_else(|e| e.into_inner());
925                            slot.push_str(&text);
926                            keep_tail(&mut slot, STDERR_KEEP);
927                        }
928                    }
929                }
930            });
931        }
932        let (tx, rx) = mpsc::sync_channel(LINE_QUEUE);
933        std::thread::spawn(move || {
934            let mut reader = BufReader::new(stdout);
935            loop {
936                let line = match read_line_capped(&mut reader, MAX_LINE) {
937                    Ok(Some(Line::Text(line))) => line,
938                    // A line this build cannot keep is a message the caller never sees; saying so is
939                    // better than a request that waits out its timeout for an answer already thrown
940                    // away (`#418`).
941                    Ok(Some(Line::TooLong(bytes))) => {
942                        if tx
943                            .send(json!({
944                                "eclipse_unparsable": format!(
945                                    "a line of {bytes} bytes is over the {MAX_LINE}-byte limit and was dropped"
946                                )
947                            }))
948                            .is_err()
949                        {
950                            break;
951                        }
952                        continue;
953                    }
954                    Ok(None) | Err(_) => break,
955                };
956                if line.trim().is_empty() {
957                    continue;
958                }
959                // A server that writes a line this build cannot parse is not silent: the caller
960                // gets "not JSON" rather than a timeout three minutes later.
961                match serde_json::from_str::<Value>(&line) {
962                    Ok(value) => {
963                        if tx.send(value).is_err() {
964                            break;
965                        }
966                    }
967                    Err(e) => {
968                        let _ = tx.send(json!({
969                            "eclipse_unparsable": format!("{e}: {}", clip(&line, 200))
970                        }));
971                    }
972                }
973            }
974        });
975        let mut pipe = Pipe { child, stdin, rx };
976        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
977        let init = json!({
978            "jsonrpc": "2.0",
979            "id": id,
980            "method": "initialize",
981            "params": {
982                "protocolVersion": PROTOCOL,
983                "capabilities": {},
984                "clientInfo": { "name": "eclipse", "version": env!("CARGO_PKG_VERSION") },
985            }
986        });
987        self.write_stdin(&mut pipe.stdin, &init.to_string())
988            .map_err(|e| {
989                format!(
990                    "could not send `initialize`: {e}{}",
991                    self.stderr_tail_soon()
992                )
993            })?;
994        let answer = wait_for(&mut pipe, id, self.timeout, &self.stderr)?;
995        if let Some(result) = answer.get("result") {
996            if result
997                .get("protocolVersion")
998                .and_then(Value::as_str)
999                .is_none()
1000            {
1001                return Err("`initialize` answered without a protocolVersion".into());
1002            }
1003            self.keep_handshake(result);
1004        }
1005        // Required by the protocol once the client is satisfied, and servers do wait for it before
1006        // answering `tools/list`.
1007        let ready = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
1008        self.write_stdin(&mut pipe.stdin, &ready.to_string())
1009            .map_err(|e| format!("could not finish the handshake: {e}"))?;
1010        Ok(pipe)
1011    }
1012
1013    fn cwd(&self) -> PathBuf {
1014        match self.spec.cwd {
1015            crate::plugins::Cwd::Plugin => self.plugin_dir.clone(),
1016            crate::plugins::Cwd::Workspace => self.workspace.clone(),
1017        }
1018    }
1019
1020    /// [`stderr_tail`](Self::stderr_tail) for a pipe that has just failed: the reader thread may not
1021    /// have been scheduled yet, and "Broken pipe" alone is a much worse error than the server's own
1022    /// complaint that follows it a millisecond later. Waits up to 200 ms, and only when the tail is
1023    /// still empty.
1024    fn stderr_tail_soon(&self) -> String {
1025        let mut tail = self.stderr_tail();
1026        // 200 ms was not always enough for a thread to be *scheduled* on a loaded machine, and the
1027        // test that asserts this text went red about once a full-suite run. Half a second costs
1028        // nothing on the happy path — the loop breaks as soon as there is something to say.
1029        for _ in 0..50 {
1030            if !tail.is_empty() {
1031                break;
1032            }
1033            std::thread::sleep(Duration::from_millis(10));
1034            tail = self.stderr_tail();
1035        }
1036        tail
1037    }
1038
1039    fn stderr_tail(&self) -> String {
1040        let slot = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
1041        let tail = slot.trim();
1042        if tail.is_empty() {
1043            String::new()
1044        } else {
1045            format!("; the server said: {}", clip(tail, 600))
1046        }
1047    }
1048}
1049
1050/// The answer to one POST: the JSON-RPC message, and the session id the server may have issued.
1051struct Reply {
1052    value: Value,
1053    session: Option<String>,
1054}
1055
1056/// What an HTTP exchange needs from the connection, cloned out so the exchange can own it: the
1057/// connection itself is borrowed by the caller and the exchange runs in its own thread.
1058struct Exchange {
1059    client: reqwest::Client,
1060    url: String,
1061    session: Option<String>,
1062    token: Option<String>,
1063    expired: Arc<AtomicBool>,
1064}
1065
1066/// The whole HTTP exchange, on a runtime this thread builds and drops (`#502`).
1067fn over_http(
1068    exchange: Exchange,
1069    body: Value,
1070    id: Option<i64>,
1071    timeout: Duration,
1072) -> Result<Reply, String> {
1073    let Exchange {
1074        client,
1075        url,
1076        session,
1077        token,
1078        expired,
1079    } = exchange;
1080    let runtime = tokio::runtime::Builder::new_current_thread()
1081        .enable_all()
1082        .build()
1083        .map_err(|e| format!("could not start an HTTP runtime: {e}"))?;
1084    runtime.block_on(async move {
1085        let mut request = client
1086            .post(&url)
1087            .header(
1088                reqwest::header::ACCEPT,
1089                "application/json, text/event-stream",
1090            )
1091            .timeout(timeout)
1092            .json(&body);
1093        if let Some(session) = session.as_deref() {
1094            request = request.header("mcp-session-id", session);
1095        }
1096        if let Some(token) = token.as_deref() {
1097            request = request.bearer_auth(token);
1098        }
1099        let response = request
1100            .send()
1101            .await
1102            .map_err(|e| format!("could not post to {url}: {e:?}"))?;
1103        let status = response.status();
1104        let issued = response
1105            .headers()
1106            .get("mcp-session-id")
1107            .and_then(|v| v.to_str().ok())
1108            .filter(|v| !v.is_empty())
1109            .map(str::to_string);
1110        let streamed = response
1111            .headers()
1112            .get(reqwest::header::CONTENT_TYPE)
1113            .and_then(|v| v.to_str().ok())
1114            .map(|v| v.contains("text/event-stream"))
1115            .unwrap_or(false);
1116        // A body with no ceiling is the one thing here that can exhaust memory before the timeout
1117        // fires; stdio already refuses a line this long (`#568`). Read it in chunks and stop.
1118        let mut response = response;
1119        let mut text = String::new();
1120        while let Some(bytes) = response
1121            .chunk()
1122            .await
1123            .map_err(|e| format!("could not read the answer from {url}: {e}"))?
1124        {
1125            if text.len() + bytes.len() > MAX_LINE {
1126                return Err(format!(
1127                    "the server answered with more than {} MiB: {url}",
1128                    MAX_LINE / (1024 * 1024)
1129                ));
1130            }
1131            text.push_str(&String::from_utf8_lossy(&bytes));
1132        }
1133        let session = issued.or(session);
1134        if status == reqwest::StatusCode::NOT_FOUND && session.is_some() {
1135            // Streamable HTTP: `404` is how a server says it has never heard of this session id — it
1136            // restarted, or the session timed out. Reusing the id fails every call until Eclipse
1137            // restarts, so the connection is marked for dropping instead (`#568`).
1138            expired.store(true, Ordering::Relaxed);
1139        }
1140        if !status.is_success() {
1141            // No child process and no stderr to harvest: the status and the body *are* the report.
1142            return Err(format!(
1143                "the server answered HTTP {}: {}",
1144                status.as_u16(),
1145                if text.trim().is_empty() {
1146                    "no body".to_string()
1147                } else {
1148                    clip(text.trim(), 400)
1149                }
1150            ));
1151        }
1152        if text.trim().is_empty() {
1153            // A notification is answered with `202 Accepted` and no body; that is a success.
1154            return Ok(Reply {
1155                value: Value::Null,
1156                session,
1157            });
1158        }
1159        let value = if streamed {
1160            sse_payload(&text, id)
1161        } else {
1162            serde_json::from_str::<Value>(text.trim()).map_err(|e| {
1163                format!(
1164                    "the server answered with a body that is not JSON-RPC ({e}): {}",
1165                    clip(text.trim(), 200)
1166                )
1167            })?
1168        };
1169        Ok(Reply { value, session })
1170    })
1171}
1172
1173/// The JSON-RPC message inside an event stream.
1174///
1175/// Streamable HTTP answers a `POST` with `text/event-stream`: one event per message, its JSON on
1176/// `data:` lines. This picks the message whose id is `id`, and for a notification — which carries
1177/// no id — the last message in the stream. An event with no `data:` is a keep-alive or a comment.
1178fn sse_payload(text: &str, id: Option<i64>) -> Value {
1179    // A CRLF stream separates events with `\r\n\r\n`, which contains no `\n\n`: every `data:` line
1180    // fell into one buffer, so a notification followed by the reply became one unparsable blob and
1181    // the id never matched — "answered with a message for another id" on a perfectly good server
1182    // (`#567`). The spec allows either line ending, so they are normalised once, here.
1183    let text = text.replace("\r\n", "\n").replace('\r', "\n");
1184    let mut last = Value::Null;
1185    for event in text.split("\n\n") {
1186        let mut data = String::new();
1187        for line in event.lines() {
1188            if let Some(rest) = line.strip_prefix("data:") {
1189                if !data.is_empty() {
1190                    data.push('\n');
1191                }
1192                data.push_str(rest.trim_start());
1193            }
1194        }
1195        if data.trim().is_empty() {
1196            continue;
1197        }
1198        let Ok(value) = serde_json::from_str::<Value>(data.trim()) else {
1199            continue;
1200        };
1201        if let Some(id) = id {
1202            if value.get("id").and_then(Value::as_i64) == Some(id) {
1203                return value;
1204            }
1205        }
1206        last = value;
1207    }
1208    last
1209}
1210
1211/// What a message from a server is, with respect to the request being waited for.
1212enum Answer {
1213    /// Not this request's answer: a notification (`notifications/tools/list_changed`), or the
1214    /// answer to a message this build has already given up on. On a pipe both arrive at the same
1215    /// place and the id is the only thing that says which is which.
1216    NotMine,
1217    /// A line that could not be parsed as JSON.
1218    Unparsable(String),
1219    /// The answer.
1220    Value(Value),
1221    /// The server's own error for this request.
1222    Failed(String),
1223}
1224
1225fn answer_to(value: &Value, id: i64, method: &str) -> Answer {
1226    if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1227        return Answer::Unparsable(why.to_string());
1228    }
1229    if value.get("id").and_then(Value::as_i64) != Some(id) {
1230        return Answer::NotMine;
1231    }
1232    if let Some(err) = value.get("error") {
1233        let message = err
1234            .get("message")
1235            .and_then(Value::as_str)
1236            .unwrap_or("no message");
1237        return Answer::Failed(format!("{method} failed: {message}"));
1238    }
1239    Answer::Value(value.get("result").cloned().unwrap_or(Value::Null))
1240}
1241
1242/// Wait for the answer to `id` on a connection that is not yet in `state` (the handshake).
1243fn wait_for(
1244    pipe: &mut Pipe,
1245    id: i64,
1246    timeout: Duration,
1247    stderr: &Arc<Mutex<String>>,
1248) -> Result<Value, String> {
1249    let deadline = Instant::now() + timeout;
1250    loop {
1251        let left = deadline.saturating_duration_since(Instant::now());
1252        match pipe.rx.recv_timeout(left) {
1253            Ok(value) => {
1254                if let Some(why) = value.get("eclipse_unparsable").and_then(Value::as_str) {
1255                    return Err(format!("the server wrote a line that is not JSON: {why}"));
1256                }
1257                if value.get("id").and_then(Value::as_i64) != Some(id) {
1258                    continue;
1259                }
1260                if let Some(err) = value.get("error") {
1261                    return Err(format!(
1262                        "`initialize` was refused: {}",
1263                        err.get("message")
1264                            .and_then(Value::as_str)
1265                            .unwrap_or("no message")
1266                    ));
1267                }
1268                return Ok(value);
1269            }
1270            Err(RecvTimeoutError::Timeout) => {
1271                let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1272                return Err(format!(
1273                    "the server did not answer `initialize` within {}s{}",
1274                    timeout.as_secs(),
1275                    if tail.trim().is_empty() {
1276                        String::new()
1277                    } else {
1278                        format!("; it said: {}", clip(tail.trim(), 600))
1279                    }
1280                ));
1281            }
1282            Err(RecvTimeoutError::Disconnected) => {
1283                let tail = stderr.lock().unwrap_or_else(|e| e.into_inner()).clone();
1284                return Err(format!(
1285                    "the server exited during the handshake{}",
1286                    if tail.trim().is_empty() {
1287                        String::new()
1288                    } else {
1289                        format!("; it said: {}", clip(tail.trim(), 600))
1290                    }
1291                ));
1292            }
1293        }
1294    }
1295}
1296
1297/// The text a `tools/call` result carries. Anything that is not text (an image, an embedded
1298/// resource) is named rather than dropped: silently losing half an answer is worse than saying the
1299/// dashboard cannot show it.
1300fn content_text(result: &Value) -> String {
1301    let Some(items) = result.get("content").and_then(Value::as_array) else {
1302        // Some servers answer with a bare string or with `structuredContent`; take what is there.
1303        if let Some(text) = result.get("content").and_then(Value::as_str) {
1304            return text.to_string();
1305        }
1306        if let Some(structured) = result.get("structuredContent") {
1307            return structured.to_string();
1308        }
1309        return String::new();
1310    };
1311    let mut parts = Vec::new();
1312    for item in items {
1313        let kind = item
1314            .get("type")
1315            .and_then(Value::as_str)
1316            .unwrap_or("unknown");
1317        if kind == "text" {
1318            if let Some(text) = item.get("text").and_then(Value::as_str) {
1319                parts.push(text.to_string());
1320            }
1321        } else {
1322            parts.push(format!("[{kind} content from an MCP server is not shown]"));
1323        }
1324    }
1325    parts.join("\n")
1326}
1327
1328/// Keep the last `keep` bytes of a log slot, never splitting a character.
1329///
1330/// `drain` takes a *byte* range and panics on an index that is not a char boundary. A 1024-byte read
1331/// frame lands mid-character routinely for non-ASCII log output, so the cut moves forward to the next
1332/// boundary: the reader thread dying here is not a lost log line, it is stderr nobody drains and a
1333/// child blocked on a full pipe (`#564`).
1334fn keep_tail(slot: &mut String, keep: usize) {
1335    if slot.len() <= keep {
1336        return;
1337    }
1338    let mut cut = slot.len() - keep;
1339    while !slot.is_char_boundary(cut) {
1340        cut += 1;
1341    }
1342    slot.drain(..cut);
1343}
1344
1345fn clip(text: &str, max: usize) -> String {
1346    if text.chars().count() <= max {
1347        return text.to_string();
1348    }
1349    let head: String = text.chars().take(max).collect();
1350    format!("{head}…")
1351}
1352
1353/// A tool the agent can call, implemented by a remote MCP server.
1354pub struct McpTool {
1355    /// The name this build registered (`prefix` + the server's name).
1356    name: String,
1357    /// The name the server knows.
1358    remote: String,
1359    description: String,
1360    parameters: Value,
1361    plugin: String,
1362    server: Arc<Server>,
1363}
1364
1365/// The most a tool name may be. OpenAI-compatible endpoints cap it at 64 characters and reject the
1366/// whole request past it — the same ceiling the config's tool ids live under.
1367pub const TOOL_NAME_MAX: usize = 64;
1368
1369/// What a remote description is cut to. A description is worth a sentence or two of prompt; a
1370/// server that sends its whole README should not get to charge that to every request.
1371pub const DESCRIPTION_MAX: usize = 2000;
1372
1373/// What a remote input schema may serialize to. See `McpTool::new` for what happens past it.
1374pub const SCHEMA_MAX: usize = 16 * 1024;
1375
1376/// A remote tool name, made safe to put in a chat request.
1377///
1378/// A third-party server names its own tools, and a name is not a private detail: it is copied into
1379/// the `tools` array of every request, and one name outside `[A-Za-z0-9_-]` makes an
1380/// OpenAI-compatible endpoint reject the entire request — so the agent is unusable and the error
1381/// names the model, not the server. Anything outside the alphabet becomes `_`, and the result is
1382/// truncated to `TOOL_NAME_MAX`; the raw name still goes to the server on the wire.
1383pub fn sanitize_tool_name(name: &str) -> String {
1384    let cleaned: String = name
1385        .chars()
1386        .map(|c| {
1387            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
1388                c
1389            } else {
1390                '_'
1391            }
1392        })
1393        .collect();
1394    cleaned.chars().take(TOOL_NAME_MAX).collect()
1395}
1396
1397/// Text cut to at most `max` **chars**, with a mark saying it was cut, so a truncated description
1398/// cannot be mistaken for the whole one.
1399fn cap_text(text: &str, max: usize) -> String {
1400    if text.chars().count() <= max {
1401        return text.to_string();
1402    }
1403    let mut out: String = text.chars().take(max).collect();
1404    out.push_str("… [truncated]");
1405    out
1406}
1407
1408impl McpTool {
1409    /// The one path a call goes through. The pipe blocks, so it runs on a blocking thread — and the
1410    /// run's cancellation flag travels with it, because a cancelled run must not sit here for a
1411    /// minute waiting for an answer nothing will read.
1412    async fn call_unless(
1413        &self,
1414        args: Value,
1415        cancel: crate::cancel::Cancel,
1416    ) -> Result<String, ToolError> {
1417        let server = Arc::clone(&self.server);
1418        let remote = self.remote.clone();
1419        let out =
1420            tokio::task::spawn_blocking(move || server.call_tool_unless(&remote, &args, &cancel))
1421                .await
1422                .map_err(|e| ToolError::Failed(format!("the MCP call did not finish: {e}")))?;
1423        out.map_err(ToolError::Failed)
1424    }
1425
1426    pub fn new(server: Arc<Server>, remote: &RemoteTool) -> Self {
1427        // `#373`: a remote name goes into the `tools` array of every chat request, and an
1428        // OpenAI-compatible server rejects the *whole request* with a 400 on the first name outside
1429        // `[A-Za-z0-9_-]` — one third-party server, one advertised `a.b` or `get repo`, and the
1430        // session is unusable with an error that names no server. Plugin command tools are already
1431        // held to that alphabet; a server's tools are held to it here, and the raw name is kept for
1432        // the wire (`remote`), which is the only place it is correct.
1433        let name = sanitize_tool_name(&format!("{}{}", server.prefix(), remote.name));
1434        let description = if remote.description.trim().is_empty() {
1435            format!("`{}` on the `{}` MCP server", remote.name, server.name())
1436        } else {
1437            cap_text(&remote.description, DESCRIPTION_MAX)
1438        };
1439        let parameters = remote
1440            .input_schema
1441            .clone()
1442            .unwrap_or_else(|| json!({ "type": "object", "properties": {} }));
1443        // A tool's schema is copied into the prompt verbatim; a server that ships a megabyte of it
1444        // costs that much of every request in the session. Past the cap the model is told the tool
1445        // takes an object and the description says so — better than a prompt nobody can afford, and
1446        // better than a silent downgrade the model has no way to notice.
1447        let over_cap = serde_json::to_string(&parameters).map_or(0, |s| s.len()) > SCHEMA_MAX;
1448        let parameters = if over_cap {
1449            json!({ "type": "object", "properties": {} })
1450        } else {
1451            parameters
1452        };
1453        let description = if over_cap {
1454            format!(
1455                "{description} [its input schema is over {SCHEMA_MAX} bytes and was not included; \
1456                 the tool takes a JSON object]"
1457            )
1458        } else {
1459            description
1460        };
1461        Self {
1462            name,
1463            remote: remote.name.clone(),
1464            description,
1465            parameters,
1466            plugin: server.name().to_string(),
1467            server,
1468        }
1469    }
1470    /// A server's own name, for a message that has to name where a tool came from.
1471    pub fn server_name(&self) -> &str {
1472        &self.plugin
1473    }
1474}
1475
1476#[async_trait::async_trait]
1477impl Tool for McpTool {
1478    fn name(&self) -> &str {
1479        &self.name
1480    }
1481
1482    fn description(&self) -> &str {
1483        &self.description
1484    }
1485
1486    fn parameters(&self) -> Value {
1487        self.parameters.clone()
1488    }
1489
1490    fn describe_call(&self, args: &Value) -> String {
1491        // The prompt has to say *which* server this is going to: `read_text_file` is a harmless name
1492        // on a filesystem server and something else entirely elsewhere.
1493        format!(
1494            "{} (mcp: {}) {}",
1495            self.remote,
1496            self.plugin,
1497            clip(&args.to_string(), 200)
1498        )
1499    }
1500
1501    async fn call(&self, args: Value) -> Result<String, ToolError> {
1502        self.call_unless(args, crate::cancel::Cancel::new()).await
1503    }
1504
1505    async fn call_scoped(
1506        &self,
1507        args: Value,
1508        scope: &crate::tools::CallScope<'_>,
1509    ) -> Result<String, ToolError> {
1510        // The run's own flag: a cancelled run must not sit waiting for a server that is still
1511        // thinking, and the answer would have nowhere to go anyway.
1512        self.call_unless(args, scope.run.cancel.clone()).await
1513    }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518    use super::*;
1519    use std::path::PathBuf;
1520
1521    /// The default a `[[mcp]]` entry with no `timeout_secs` would get. The tests all state their
1522    /// own ceiling in the spec, so this only has to be a sane number.
1523    const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
1524
1525    /// A server that speaks just enough of the protocol, so the client can be tested without a
1526    /// network or a real MCP implementation. `sleep` on a call hangs it, which is what a timeout is
1527    /// for; two pages of tools exercise `nextCursor`.
1528    const FAKE: &str = r#"#!/usr/bin/env python3
1529import json, sys, time
1530
1531def send(obj):
1532    sys.stdout.write(json.dumps(obj) + "\n"); sys.stdout.flush()
1533
1534for line in sys.stdin:
1535    line = line.strip()
1536    if not line:
1537        continue
1538    msg = json.loads(line)
1539    mid, method = msg.get("id"), msg.get("method")
1540    params = msg.get("params") or {}
1541    if method == "initialize":
1542        send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
1543              "capabilities": {"tools": {}}, "serverInfo": {"name": "fake", "version": "0"}}})
1544    elif method == "notifications/initialized":
1545        pass
1546    elif method == "tools/list":
1547        if params.get("cursor"):
1548            send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1549                {"name": "fail_tool", "description": "Always fails"}]}})
1550        else:
1551            send({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
1552                {"name": "echo_text", "description": "Echo the text back",
1553                 "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
1554                "nextCursor": "page-2"}})
1555    elif method == "tools/call":
1556        name, args = params.get("name"), params.get("arguments") or {}
1557        if name == "echo_text":
1558            if args.get("sleep"):
1559                time.sleep(30)
1560            send({"jsonrpc": "2.0", "id": mid, "result": {"content": [
1561                {"type": "text", "text": "echo: " + str(args.get("text", ""))}]}})
1562        elif name == "fail_tool":
1563            send({"jsonrpc": "2.0", "id": mid, "result": {
1564                "content": [{"type": "text", "text": "the disk is on fire"}], "isError": True}})
1565        else:
1566            send({"jsonrpc": "2.0", "id": mid, "result": {"content": []}})
1567    elif mid is not None:
1568        send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "no such method"}})
1569"#;
1570
1571    /// A Streamable HTTP server, hand-rolled on a socket (`#502`).
1572    ///
1573    /// The subject here is the *transport*, not MCP: what a real server does with a message is
1574    /// already covered by `FAKE`. So this answers from the request line and the body alone, and it
1575    /// answers in the two shapes the protocol allows — a JSON body for `tools/call`, an event
1576    /// stream for `tools/list` — so both parsers are exercised by one passing run.
1577    struct FakeHttp {
1578        port: u16,
1579        seen: Arc<Mutex<Vec<(String, String)>>>,
1580        stop: Arc<std::sync::atomic::AtomicBool>,
1581        /// Set from the test thread: from then on every request that carries a session id is
1582        /// answered `404`, which is how a Streamable HTTP server says it has forgotten it (`#568`).
1583        forgetful: Arc<std::sync::atomic::AtomicBool>,
1584    }
1585
1586    impl Drop for FakeHttp {
1587        fn drop(&mut self) {
1588            self.stop.store(true, Ordering::SeqCst);
1589            // Unblock the accept: a connection that is never answered is the thread's exit ticket.
1590            let _ = std::net::TcpStream::connect(("127.0.0.1", self.port));
1591        }
1592    }
1593
1594    impl FakeHttp {
1595        /// Make the server forget every session it has issued, the way a restart does (`#568`).
1596        fn forget_sessions(&self) {
1597            self.forgetful.store(true, Ordering::SeqCst);
1598        }
1599
1600        /// `token`: when set, the server answers 401 unless the request carries it.
1601        fn start(token: Option<String>, status: Option<u16>) -> Self {
1602            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a port");
1603            let port = listener.local_addr().unwrap().port();
1604            let seen = Arc::new(Mutex::new(Vec::new()));
1605            let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1606            let forgetful = Arc::new(std::sync::atomic::AtomicBool::new(false));
1607            let (log, flag) = (Arc::clone(&seen), Arc::clone(&stop));
1608            let forget = Arc::clone(&forgetful);
1609            std::thread::spawn(move || {
1610                for stream in listener.incoming() {
1611                    if flag.load(Ordering::SeqCst) {
1612                        break;
1613                    }
1614                    let Ok(mut stream) = stream else { continue };
1615                    let (head, body) = read_http(&mut stream);
1616                    log.lock()
1617                        .unwrap_or_else(|e| e.into_inner())
1618                        .push((head.clone(), body.clone()));
1619                    let reply = answer_http(&head, &body, token.as_deref(), status, &forget);
1620                    let _ = std::io::Write::write_all(&mut stream, reply.as_bytes());
1621                    let _ = std::io::Write::flush(&mut stream);
1622                }
1623            });
1624            FakeHttp {
1625                port,
1626                seen,
1627                stop,
1628                forgetful,
1629            }
1630        }
1631
1632        fn url(&self, path: &str) -> String {
1633            format!("http://127.0.0.1:{}{path}", self.port)
1634        }
1635
1636        fn requests(&self) -> Vec<(String, String)> {
1637            self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone()
1638        }
1639    }
1640
1641    /// Read one request: the head, and `Content-Length` bytes of body.
1642    fn read_http(stream: &mut std::net::TcpStream) -> (String, String) {
1643        use std::io::Read;
1644        let mut head = Vec::new();
1645        let mut byte = [0u8; 1];
1646        while head.len() < 64 * 1024 {
1647            match stream.read(&mut byte) {
1648                Ok(0) | Err(_) => {
1649                    return (String::from_utf8_lossy(&head).into_owned(), String::new())
1650                }
1651                Ok(_) => {
1652                    head.push(byte[0]);
1653                    if head.ends_with(b"\r\n\r\n") {
1654                        break;
1655                    }
1656                }
1657            }
1658        }
1659        let head = String::from_utf8_lossy(&head).into_owned();
1660        let length = head
1661            .lines()
1662            .find_map(|line| {
1663                let (name, value) = line.split_once(':')?;
1664                name.eq_ignore_ascii_case("content-length")
1665                    .then(|| value.trim().parse::<usize>().ok())
1666                    .flatten()
1667            })
1668            .unwrap_or(0);
1669        let mut body = vec![0u8; length];
1670        let mut got = 0;
1671        while got < length {
1672            match stream.read(&mut body[got..]) {
1673                Ok(0) | Err(_) => break,
1674                Ok(n) => got += n,
1675            }
1676        }
1677        body.truncate(got);
1678        (head, String::from_utf8_lossy(&body).into_owned())
1679    }
1680
1681    fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {
1682        head.lines().find_map(|line| {
1683            let (key, value) = line.split_once(':')?;
1684            key.eq_ignore_ascii_case(name).then(|| value.trim())
1685        })
1686    }
1687
1688    fn answer_http(
1689        head: &str,
1690        body: &str,
1691        token: Option<&str>,
1692        status: Option<u16>,
1693        forgetful: &std::sync::atomic::AtomicBool,
1694    ) -> String {
1695        let message: Value = serde_json::from_str(body).unwrap_or(Value::Null);
1696        let id = message.get("id").cloned().unwrap_or(Value::Null);
1697        let method = message.get("method").and_then(Value::as_str).unwrap_or("");
1698        if let Some(token) = token {
1699            let sent = header(head, "authorization").unwrap_or("<>");
1700            if sent != format!("Bearer {token}") {
1701                return http_reply(
1702                    401,
1703                    "application/json",
1704                    &json!({ "error": "unauthorized" }).to_string(),
1705                    "",
1706                );
1707            }
1708        }
1709        if let Some(status) = status {
1710            return http_reply(status, "application/json", "", "");
1711        }
1712        // A server that has restarted knows no sessions: everything but a fresh `initialize` is
1713        // answered `404` (`#568`).
1714        if forgetful.load(Ordering::SeqCst) && method != "initialize" {
1715            return http_reply(404, "application/json", "", "");
1716        }
1717        // The session id is the whole point of the handshake: everything after `initialize` must
1718        // carry it back.
1719        if method != "initialize" && header(head, "mcp-session-id").is_none() {
1720            return http_reply(400, "application/json", "", "");
1721        }
1722        match method {
1723            "initialize" => {
1724                let extra = "mcp-session-id: test-session\r\n";
1725                http_reply(
1726                    200,
1727                    "application/json",
1728                    &json!({ "jsonrpc": "2.0", "id": id, "result": {
1729                        "protocolVersion": "2024-11-05",
1730                        "capabilities": { "tools": {} },
1731                        "serverInfo": { "name": "fake-http", "version": "0" } } })
1732                    .to_string(),
1733                    extra,
1734                )
1735            }
1736            // A notification is answered with an accepted-and-empty body.
1737            "notifications/initialized" => http_reply(202, "text/plain", "", ""),
1738            "tools/list" => {
1739                let page = message
1740                    .get("params")
1741                    .and_then(|p| p.get("cursor"))
1742                    .and_then(Value::as_str)
1743                    .map(str::to_string);
1744                let result = match page.as_deref() {
1745                    Some("page-2") => json!({ "tools": [
1746                        { "name": "fail_tool", "description": "Always fails" }] }),
1747                    _ => json!({ "tools": [
1748                        { "name": "echo_text", "description": "Echo the text back",
1749                          "inputSchema": { "type": "object",
1750                            "properties": { "text": { "type": "string" } } } }],
1751                        "nextCursor": "page-2" }),
1752                };
1753                // An event stream, with a keep-alive comment first: a parser that treats every
1754                // line as a message would answer with null here.
1755                let event = format!(
1756                    ": keep-alive\n\ndata: {}\n\n",
1757                    json!({ "jsonrpc": "2.0", "id": id, "result": result })
1758                );
1759                http_reply(200, "text/event-stream", &event, "")
1760            }
1761            "tools/call" => {
1762                let name = message
1763                    .get("params")
1764                    .and_then(|p| p.get("name"))
1765                    .and_then(Value::as_str)
1766                    .unwrap_or("");
1767                let text = message
1768                    .get("params")
1769                    .and_then(|p| p.get("arguments"))
1770                    .and_then(|a| a.get("text"))
1771                    .and_then(Value::as_str)
1772                    .unwrap_or("");
1773                let result = if name == "fail_tool" {
1774                    json!({ "content": [{ "type": "text", "text": "the disk is on fire" }],
1775                            "isError": true })
1776                } else {
1777                    json!({ "content": [{ "type": "text", "text": format!("echo: {text}") }] })
1778                };
1779                http_reply(
1780                    200,
1781                    "application/json",
1782                    &json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string(),
1783                    "",
1784                )
1785            }
1786            _ => http_reply(
1787                200,
1788                "application/json",
1789                &json!({ "jsonrpc": "2.0", "id": id,
1790                        "error": { "code": -32601, "message": "no such method" } })
1791                .to_string(),
1792                "",
1793            ),
1794        }
1795    }
1796
1797    fn http_reply(status: u16, kind: &str, body: &str, extra: &str) -> String {
1798        format!(
1799            "HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
1800            body.len()
1801        )
1802    }
1803
1804    /// An HTTP entry with the fields the transport needs, and nothing else.
1805    fn http_spec(url: &str) -> Spec {
1806        Spec {
1807            name: "ha".into(),
1808            transport: Transport::Http,
1809            command: String::new(),
1810            args: Vec::new(),
1811            env: Vec::new(),
1812            cwd: crate::plugins::Cwd::Workspace,
1813            url: Some(url.to_string()),
1814            token_env: None,
1815            timeout_secs: Some(10),
1816            policy: Policy::Allow,
1817            policies: BTreeMap::new(),
1818            prefix: String::new(),
1819            override_builtin: false,
1820            disabled: false,
1821        }
1822    }
1823
1824    /// A server that dies before saying anything: the failure has to arrive as an error with the
1825    /// reason, not as a hang.
1826    const DIES: &str = r#"#!/usr/bin/env python3
1827import sys
1828sys.stderr.write("could not open the database: /nope\n")
1829sys.exit(3)
1830"#;
1831
1832    fn have_python() -> bool {
1833        std::process::Command::new("python3")
1834            .arg("--version")
1835            .output()
1836            .map(|o| o.status.success())
1837            .unwrap_or(false)
1838    }
1839
1840    fn script(dir: &Path, name: &str, body: &str) -> PathBuf {
1841        let path = dir.join(name);
1842        std::fs::write(&path, body).unwrap();
1843        #[cfg(unix)]
1844        {
1845            use std::os::unix::fs::PermissionsExt;
1846            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1847        }
1848        path
1849    }
1850
1851    fn spec(script: &Path, timeout_secs: u64) -> Spec {
1852        Spec {
1853            name: "fake".into(),
1854            transport: Transport::Stdio,
1855            command: "python3".into(),
1856            args: vec![script.to_string_lossy().into_owned()],
1857            url: None,
1858            token_env: None,
1859            env: Vec::new(),
1860            cwd: crate::plugins::Cwd::Plugin,
1861            timeout_secs: Some(timeout_secs),
1862            policy: Policy::Ask,
1863            policies: Default::default(),
1864            prefix: String::new(),
1865            override_builtin: false,
1866            disabled: false,
1867        }
1868    }
1869
1870    /// `#373`: a remote server names its own tools, and that name is copied into the `tools` array of
1871    /// every chat request. An OpenAI-compatible endpoint rejects the *whole request* on the first name
1872    /// outside `[A-Za-z0-9_-]`, so one third-party server advertising `get repo` left the agent
1873    /// unusable for the session with an error naming the model rather than the server.
1874    #[test]
1875    fn a_remote_tool_name_is_made_safe_for_a_request() {
1876        // The alphabet is the one plugin command tools are already held to.
1877        assert_eq!(sanitize_tool_name("get repo"), "get_repo");
1878        assert_eq!(sanitize_tool_name("a.b"), "a_b");
1879        assert_eq!(sanitize_tool_name("日本"), "__");
1880        assert_eq!(sanitize_tool_name("read_file"), "read_file");
1881        // Long names are cut, not rejected: a 64-character ceiling is what the endpoint enforces.
1882        let long = "x".repeat(200);
1883        assert_eq!(sanitize_tool_name(&long).chars().count(), TOOL_NAME_MAX);
1884        assert_eq!(
1885            sanitize_tool_name(&format!("{}_tail", "y".repeat(63)))
1886                .chars()
1887                .count(),
1888            TOOL_NAME_MAX
1889        );
1890
1891        // A description and a schema are copied into the prompt too.
1892        let long_desc = "d".repeat(DESCRIPTION_MAX * 2);
1893        let capped = cap_text(&long_desc, DESCRIPTION_MAX);
1894        assert!(capped.starts_with(&"d".repeat(DESCRIPTION_MAX)));
1895        assert!(capped.ends_with("[truncated]"), "{capped}");
1896        assert_eq!(cap_text("short", DESCRIPTION_MAX), "short");
1897    }
1898
1899    /// The name the endpoint sees is safe; the name the *server* is asked for is the one it
1900    /// published — those are two different strings and both have to be right.
1901    #[test]
1902    fn the_wire_keeps_the_name_the_server_published() {
1903        if !have_python() {
1904            return;
1905        }
1906        let dir = tempfile::tempdir().unwrap();
1907        let path = script(dir.path(), "fake.py", FAKE);
1908        let (server, _tools) = Server::start(
1909            &spec(&path, 10),
1910            dir.path(),
1911            dir.path(),
1912            DEFAULT_TEST_TIMEOUT,
1913            &Secrets::new(),
1914        )
1915        .expect("the fake server starts");
1916        let remote = RemoteTool {
1917            name: "get repo".into(),
1918            description: "Read a repository".into(),
1919            input_schema: None,
1920        };
1921        let tool = McpTool::new(Arc::clone(&server), &remote);
1922        assert_eq!(tool.name(), "get_repo");
1923        assert_eq!(
1924            tool.remote, "get repo",
1925            "the server is asked for the name it published, not the sanitised one"
1926        );
1927    }
1928
1929    /// `#418`: `BufReader::lines()` grew a `Vec` to whatever the writer sent, so a server that wrote
1930    /// a gigabyte without a newline cost a gigabyte before any cap was consulted. The reader keeps
1931    /// at most `MAX_LINE` bytes and counts the rest.
1932    #[test]
1933    fn a_line_over_the_cap_is_counted_and_dropped_not_buffered() {
1934        // A line that never ends, 4× the cap.
1935        let big = vec![b'x'; MAX_LINE * 4];
1936        let mut reader = BufReader::new(&big[..]);
1937        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1938            Some(Line::TooLong(bytes)) => assert_eq!(bytes, MAX_LINE * 4),
1939            Some(Line::Text(t)) => panic!("kept {} bytes of it", t.len()),
1940            None => panic!("nothing read at all"),
1941        }
1942        // And an ordinary line still arrives whole, with the newline consumed.
1943        let mut reader = BufReader::new(&b"{\"a\":1}\n{\"b\":2}\n"[..]);
1944        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1945            Some(Line::Text(text)) => assert_eq!(text, "{\"a\":1}"),
1946            other => panic!("{:?}", other.is_some()),
1947        }
1948        match read_line_capped(&mut reader, MAX_LINE).unwrap() {
1949            Some(Line::Text(text)) => assert_eq!(text, "{\"b\":2}"),
1950            _ => panic!("the second line did not survive"),
1951        }
1952        assert!(read_line_capped(&mut reader, MAX_LINE).unwrap().is_none());
1953    }
1954
1955    /// `#418`: killing only the direct child left the real server running when it was started
1956    /// through `npx`/`sh -c` — the grandchild held the stdout pipe, so the reader thread stayed
1957    /// blocked on it for the life of the process. The server is in its own process group now and
1958    /// the drop takes the tree with it.
1959    #[cfg(unix)]
1960    #[test]
1961    fn dropping_a_connection_kills_the_grandchild_holding_the_pipe() {
1962        if !have_python() {
1963            return;
1964        }
1965        let dir = tempfile::tempdir().unwrap();
1966        let fake = script(dir.path(), "fake.py", FAKE);
1967        let pid_file = dir.path().join("grandchild.pid");
1968        let wrapper = format!(
1969            "#!/bin/sh\nsleep 300 &\necho $! > {}\nexec python3 {}\n",
1970            pid_file.display(),
1971            fake.display()
1972        );
1973        let path = script(dir.path(), "wrapper.sh", &wrapper);
1974        let mut spec = spec(&fake, 10);
1975        spec.command = "sh".into();
1976        spec.args = vec![path.to_string_lossy().into_owned()];
1977        let (server, tools) = Server::start(
1978            &spec,
1979            dir.path(),
1980            dir.path(),
1981            DEFAULT_TEST_TIMEOUT,
1982            &Secrets::new(),
1983        )
1984        .expect("the wrapped server still speaks the protocol");
1985        assert_eq!(tools.len(), 2);
1986        let pid: u32 = std::fs::read_to_string(&pid_file)
1987            .expect("the wrapper recorded its child")
1988            .trim()
1989            .parse()
1990            .expect("a pid");
1991        assert!(pid_alive(pid), "the grandchild is running");
1992
1993        drop(server);
1994
1995        // The group kill is synchronous inside `Drop`, but a pid can linger as a zombie if it was
1996        // not reaped by its own parent; `pid_alive` treats a zombie as gone. What this asserts is
1997        // that the tree is gone — not that it went in the same second. The window used to be one
1998        // second, which failed about once in ten whole-suite runs on a loaded runner (`#432`) while
1999        // never failing alone: a pid is reaped when its own parent dies, and under contention that
2000        // bookkeeping is not what the scheduler is spending its time on.
2001        let mut waited = Duration::ZERO;
2002        while pid_alive(pid) && waited < Duration::from_secs(10) {
2003            std::thread::sleep(Duration::from_millis(20));
2004            waited += Duration::from_millis(20);
2005        }
2006        assert!(
2007            !pid_alive(pid),
2008            "the grandchild outlived the connection: still alive after {waited:?}"
2009        );
2010    }
2011
2012    #[cfg(unix)]
2013    fn pid_alive(pid: u32) -> bool {
2014        let Ok(pid) = libc::pid_t::try_from(pid) else {
2015            return false;
2016        };
2017        // SAFETY: signal 0 asks the kernel whether the pid exists.
2018        let rc = unsafe { libc::kill(pid, 0) };
2019        if rc != 0 {
2020            return false;
2021        }
2022        // A zombie still answers signal 0; read its state and call it gone.
2023        match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
2024            Ok(stat) => match stat.rsplit_once(')') {
2025                Some((_, rest)) => !rest.trim_start().starts_with('Z'),
2026                None => true,
2027            },
2028            Err(_) => false,
2029        }
2030    }
2031
2032    #[test]
2033    fn a_server_is_listed_across_pages_and_its_tools_can_be_called() {
2034        if !have_python() {
2035            return;
2036        }
2037        let dir = tempfile::tempdir().unwrap();
2038        let path = script(dir.path(), "fake.py", FAKE);
2039        let (server, tools) = Server::start(
2040            &spec(&path, 10),
2041            dir.path(),
2042            dir.path(),
2043            DEFAULT_TEST_TIMEOUT,
2044            &Secrets::new(),
2045        )
2046        .expect("the fake server starts");
2047        // Both pages: stopping at the first would have hidden `fail_tool` entirely.
2048        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
2049        assert_eq!(names, ["echo_text", "fail_tool"]);
2050        let echo = tools.iter().find(|t| t.name == "echo_text").unwrap();
2051        assert_eq!(echo.description, "Echo the text back");
2052        assert_eq!(echo.input_schema.as_ref().unwrap()["type"], "object");
2053
2054        // One connection for both calls: the second answer must not be read from the first's pipe.
2055        let out = server
2056            .call_tool("echo_text", &json!({"text": "one"}))
2057            .unwrap();
2058        assert_eq!(out, "echo: one");
2059        let out = server
2060            .call_tool("echo_text", &json!({"text": "two"}))
2061            .unwrap();
2062        assert_eq!(out, "echo: two");
2063
2064        // A tool that reports failure is an error the model reads, with the server's own words.
2065        let err = server.call_tool("fail_tool", &json!({})).unwrap_err();
2066        assert_eq!(err, "the disk is on fire");
2067    }
2068
2069    /// `#502`: the transport itself — list across two pages over an event stream, call over a JSON
2070    /// body, and the session id carried back on every post after `initialize`.
2071    #[test]
2072    fn an_http_entry_lists_across_pages_calls_a_tool_and_carries_the_session_id() {
2073        let fake = FakeHttp::start(None, None);
2074        let dir = tempfile::tempdir().unwrap();
2075        let (server, tools) = Server::start(
2076            &http_spec(&fake.url("/api/mcp")),
2077            dir.path(),
2078            dir.path(),
2079            DEFAULT_TEST_TIMEOUT,
2080            &Secrets::new(),
2081        )
2082        .expect("the HTTP server handshakes");
2083        let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
2084        assert_eq!(names, ["echo_text", "fail_tool"], "both pages arrived");
2085        assert_eq!(
2086            tools[0].input_schema.as_ref().unwrap()["type"],
2087            "object",
2088            "the schema survives the event-stream framing"
2089        );
2090
2091        assert_eq!(
2092            server
2093                .call_tool("echo_text", &json!({ "text": "ha" }))
2094                .unwrap(),
2095            "echo: ha"
2096        );
2097        // A tool that reports failure is an error the model reads, with the server's own words —
2098        // the same as on stdio, because that decision is above the transport.
2099        assert_eq!(
2100            server.call_tool("fail_tool", &json!({})).unwrap_err(),
2101            "the disk is on fire"
2102        );
2103
2104        let requests = fake.requests();
2105        assert_eq!(requests.len(), 6, "initialize, ready, two pages, two calls");
2106        // Every post after the handshake carries the id the server issued, or the fake answers
2107        // 400 — which is why the calls above would have failed rather than passed.
2108        for (head, _) in requests.iter().skip(1) {
2109            assert_eq!(
2110                header(head, "mcp-session-id"),
2111                Some("test-session"),
2112                "{head}"
2113            );
2114        }
2115        assert_eq!(
2116            header(&requests[0].0, "accept"),
2117            Some("application/json, text/event-stream"),
2118            "the client has to say it can read both, or a server may answer neither"
2119        );
2120        assert!(
2121            requests[0].1.contains("\"initialize\""),
2122            "{}",
2123            requests[0].1
2124        );
2125        // Page two is a `cursor` in the request: the client has to send back what it was given.
2126        assert!(
2127            requests[3].1.contains("\"cursor\""),
2128            "the second page is asked for by cursor: {}",
2129            requests[3].1
2130        );
2131    }
2132
2133    /// A server that does not accept us says so with its status, not with a timeout.
2134    #[test]
2135    fn a_401_is_reported_as_a_status_and_not_as_a_timeout() {
2136        let fake = FakeHttp::start(Some("s3cret".into()), None);
2137        let dir = tempfile::tempdir().unwrap();
2138        // A name built at runtime, so this stays a test detail rather than a variable the build
2139        // is documented to read (`every_environment_variable_the_build_reads_is_classified`).
2140        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_SET");
2141        let mut spec = http_spec(&fake.url("/api/mcp"));
2142        spec.token_env = Some(key.clone());
2143        std::env::set_var(&key, "wrong");
2144        let err = Server::start(
2145            &spec,
2146            dir.path(),
2147            dir.path(),
2148            DEFAULT_TEST_TIMEOUT,
2149            &Secrets::new(),
2150        )
2151        .expect_err("401 is not a handshake");
2152        assert!(err.contains("401"), "the status is the report: {err}");
2153        assert!(!err.contains("did not answer"), "{err}");
2154
2155        // The right token gets through — the same entry, one variable changed.
2156        std::env::set_var(&key, "s3cret");
2157        Server::start(
2158            &spec,
2159            dir.path(),
2160            dir.path(),
2161            DEFAULT_TEST_TIMEOUT,
2162            &Secrets::new(),
2163        )
2164        .expect("the right token handshakes");
2165        std::env::remove_var(&key);
2166    }
2167
2168    /// `#516`: a token in `.env` is a token. The config parses that file into `Dotenv.values` and
2169    /// never touches the process environment, so `token_env` used to be the one credential that
2170    /// could not see a secret stored where eclipse says secrets live. The assertion is on what
2171    /// went over the wire, not on a log.
2172    #[test]
2173    fn a_token_stored_only_in_dotenv_connects_and_is_what_the_client_sends() {
2174        let fake = FakeHttp::start(Some("from-file".into()), None);
2175        let dir = tempfile::tempdir().unwrap();
2176        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_DOTENV");
2177        std::env::remove_var(&key);
2178        let mut spec = http_spec(&fake.url("/api/mcp"));
2179        spec.token_env = Some(key.clone());
2180        let mut secrets = Secrets::new();
2181        secrets.insert(key, "from-file".to_string());
2182
2183        Server::start(
2184            &spec,
2185            dir.path(),
2186            dir.path(),
2187            DEFAULT_TEST_TIMEOUT,
2188            &secrets,
2189        )
2190        .expect("a token kept in `.env` is a token this build can send");
2191
2192        let sent = fake
2193            .requests()
2194            .into_iter()
2195            .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2196            .expect("the handshake carries an Authorization header");
2197        assert_eq!(sent, "Bearer from-file", "the value from `.env`, verbatim");
2198    }
2199
2200    /// The other half of the order: the process environment wins, so one run can override one
2201    /// file without editing it.
2202    #[test]
2203    fn the_environment_wins_over_dotenv_for_a_token_variable() {
2204        let fake = FakeHttp::start(Some("from-env".into()), None);
2205        let dir = tempfile::tempdir().unwrap();
2206        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_BOTH");
2207        let mut spec = http_spec(&fake.url("/api/mcp"));
2208        spec.token_env = Some(key.clone());
2209        let mut secrets = Secrets::new();
2210        secrets.insert(key.clone(), "from-file".to_string());
2211        std::env::set_var(&key, "from-env");
2212
2213        let started = Server::start(
2214            &spec,
2215            dir.path(),
2216            dir.path(),
2217            DEFAULT_TEST_TIMEOUT,
2218            &secrets,
2219        );
2220        std::env::remove_var(&key);
2221        started.expect("the environment's value is the one used");
2222
2223        let sent = fake
2224            .requests()
2225            .into_iter()
2226            .find_map(|(head, _)| header(&head, "authorization").map(str::to_string))
2227            .expect("the handshake carries an Authorization header");
2228        assert_eq!(
2229            sent, "Bearer from-env",
2230            "the environment wins over the file"
2231        );
2232    }
2233
2234    /// An empty value is absent, as it is in `Dotenv::load` — and the refusal names the variable
2235    /// without printing any other secret that happens to be resolved.
2236    #[test]
2237    fn an_empty_dotenv_token_is_absent_and_the_refusal_prints_no_secret() {
2238        let fake = FakeHttp::start(Some("s3cret".into()), None);
2239        let dir = tempfile::tempdir().unwrap();
2240        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_EMPTY");
2241        std::env::remove_var(&key);
2242        let mut spec = http_spec(&fake.url("/api/mcp"));
2243        spec.token_env = Some(key.clone());
2244        let mut secrets = Secrets::new();
2245        secrets.insert(key.clone(), String::new());
2246        secrets.insert(format!("{key}_NEIGHBOUR"), "s3cret".to_string());
2247
2248        let err = Server::start(
2249            &spec,
2250            dir.path(),
2251            dir.path(),
2252            DEFAULT_TEST_TIMEOUT,
2253            &secrets,
2254        )
2255        .expect_err("an empty value is not a token");
2256        assert!(err.contains(&key), "{err}");
2257        assert!(
2258            err.contains("never reads a token from the manifest"),
2259            "{err}"
2260        );
2261        assert!(
2262            !err.contains("s3cret"),
2263            "a refusal is not a place for a value: {err}"
2264        );
2265    }
2266
2267    /// A variable the environment does not set is an error naming it: the alternative is a 401
2268    /// that reads like the server's fault.
2269    #[test]
2270    fn a_token_variable_that_is_not_set_is_named_in_the_error() {
2271        let fake = FakeHttp::start(Some("s3cret".into()), None);
2272        let dir = tempfile::tempdir().unwrap();
2273        let key = format!("ECLIPSE_TEST_MCP_TOKEN{}", "_UNSET");
2274        let mut spec = http_spec(&fake.url("/api/mcp"));
2275        spec.token_env = Some(key.clone());
2276        std::env::remove_var(&key);
2277        let err = Server::start(
2278            &spec,
2279            dir.path(),
2280            dir.path(),
2281            DEFAULT_TEST_TIMEOUT,
2282            &Secrets::new(),
2283        )
2284        .expect_err("no token, no connection");
2285        assert!(err.contains(&key), "{err}");
2286        assert!(
2287            err.contains("never reads a token from the manifest"),
2288            "{err}"
2289        );
2290    }
2291
2292    /// The one place a `[[mcp]]` entry is checked, both ways round.
2293    #[test]
2294    fn a_manifest_that_mixes_transports_is_refused_naming_both() {
2295        // Default is stdio, so every manifest written before `#502` still means what it meant.
2296        let old: Spec = toml::from_str(
2297            "name = \"fs\"\ncommand = \"mcp-server-filesystem\"\nargs = [\"/tmp\"]\n",
2298        )
2299        .expect("an entry with no transport is a stdio entry");
2300        assert_eq!(old.transport, Transport::Stdio);
2301        assert!(old.validate().is_ok());
2302
2303        let mut both = http_spec("http://127.0.0.1:1/api/mcp");
2304        both.command = "mcp-server".into();
2305        let why = both.validate().unwrap_err();
2306        assert!(why.contains("command"), "{why}");
2307        assert!(why.contains("url"), "{why}");
2308        assert!(why.contains("stdio") && why.contains("http"), "{why}");
2309
2310        let mut no_url = http_spec("http://127.0.0.1:1/api/mcp");
2311        no_url.url = None;
2312        assert!(no_url.validate().unwrap_err().contains("no `url`"));
2313
2314        let mut no_command = old.clone();
2315        no_command.command = String::new();
2316        assert!(no_command
2317            .validate()
2318            .unwrap_err()
2319            .contains("no `command` given"));
2320
2321        // A stdio entry with a url is a mix too, and says which half to drop.
2322        let mut stray = old.clone();
2323        stray.url = Some("http://127.0.0.1:1/api/mcp".into());
2324        let why = stray.validate().unwrap_err();
2325        assert!(why.contains("command"), "{why}");
2326        assert!(why.contains("http"), "{why}");
2327
2328        // A scheme this client cannot speak is refused before anything is posted.
2329        let mut bad = http_spec("127.0.0.1:1/api/mcp");
2330        bad.transport = Transport::Http;
2331        assert!(bad.validate().unwrap_err().contains("not an http://"));
2332    }
2333
2334    /// `#564`: `drain` panics on a byte index that is not a char boundary, and a 1024-byte read frame
2335    /// lands mid-character as soon as the log is not ASCII. The thread that panics here is the one
2336    /// draining stderr: it dies, the pipe fills, and the server blocks forever.
2337    #[test]
2338    fn a_stderr_tail_is_cut_on_a_character_boundary() {
2339        // `len - STDERR_KEEP` lands on the second byte of `ě`, which is exactly the panic.
2340        let mut slot = format!("0123456789ě{}", "x".repeat(STDERR_KEEP - 1));
2341        let full = slot.len();
2342        assert_eq!(full - STDERR_KEEP, 11, "the cut lands mid-character");
2343        keep_tail(&mut slot, STDERR_KEEP);
2344        assert!(slot.len() <= STDERR_KEEP, "{}", slot.len());
2345        assert!(slot.ends_with('x'), "the tail is kept: {}", &slot[..4]);
2346    }
2347
2348    /// `#567`: a CRLF stream separates events with `\r\n\r\n`, which contains no `\n\n`. Every
2349    /// `data:` line used to land in one buffer, so a notification ahead of the reply made one
2350    /// unparsable blob and a good server was reported as "answered with a message for another id".
2351    #[test]
2352    fn a_crlf_event_stream_with_a_notification_ahead_of_the_reply_is_split() {
2353        let text = "event: message\r\n\
2354                    data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\"}\r\n\r\n\
2355                    event: message\r\n\
2356                    data: {\"jsonrpc\":\"2.0\",\"id\":9,\"result\":{\"ok\":true}}\r\n\r\n";
2357        let value = sse_payload(text, Some(9));
2358        assert_eq!(
2359            value["id"], 9,
2360            "the reply was found behind the notification"
2361        );
2362        assert_eq!(value["result"]["ok"], true);
2363    }
2364
2365    /// `#568`: `404` is how a Streamable HTTP server says it does not know the session id it was
2366    /// sent — a restart, an expired session. The id went back on every later call, so every tool
2367    /// failed until Eclipse restarted. The connection is dropped now, and the next call handshakes.
2368    #[test]
2369    fn a_404_on_the_session_makes_the_next_call_handshake_again() {
2370        let fake = FakeHttp::start(None, None);
2371        let dir = tempfile::tempdir().unwrap();
2372        let (server, _tools) = Server::start(
2373            &http_spec(&fake.url("/api/mcp")),
2374            dir.path(),
2375            dir.path(),
2376            DEFAULT_TEST_TIMEOUT,
2377            &Secrets::new(),
2378        )
2379        .expect("the handshake itself carries no session");
2380
2381        fake.forget_sessions();
2382        let first = server.call_tool("echo_text", &json!({ "text": "ha" }));
2383        assert!(first.is_err(), "the server has forgotten the session");
2384        assert!(
2385            first.unwrap_err().to_string().contains("404"),
2386            "the status is the report"
2387        );
2388
2389        let before = fake.seen.lock().unwrap().len();
2390        let _ = server.call_tool("echo_text", &json!({ "text": "ha" }));
2391        let seen = fake.seen.lock().unwrap();
2392        let after: Vec<&String> = seen[before..].iter().map(|(_, body)| body).collect();
2393        assert!(
2394            after.iter().any(|b| b.contains("\"initialize\"")),
2395            "the dead session was reused instead of replaced: {after:?}"
2396        );
2397    }
2398
2399    /// The event-stream parser: a keep-alive, a comment, and a message split over two `data:` lines
2400    /// with CRLF endings — the shapes a real server puts on the wire.
2401    #[test]
2402    fn an_event_stream_is_read_as_json_rpc() {
2403        let text = ": keep-alive\r\n\r\n\
2404                    data: {\"jsonrpc\":\"2.0\",\"id\":7,\r\n\
2405                    data: \"result\":{\"ok\":true}}\r\n\r\n";
2406        let value = sse_payload(text, Some(7));
2407        assert_eq!(value["id"], 7);
2408        assert_eq!(value["result"]["ok"], true);
2409
2410        // A message for another id is not the answer to this one, and null is not an answer at all.
2411        assert_eq!(sse_payload(text, Some(8))["id"], 7);
2412        assert_eq!(sse_payload(": nothing\r\n\r\n", Some(1)), Value::Null);
2413        // No id asked for — a notification's answer — means the last message wins.
2414        assert_eq!(sse_payload(text, None)["id"], 7);
2415    }
2416
2417    #[test]
2418    fn a_hanging_server_times_out_and_the_next_call_starts_a_fresh_one() {
2419        if !have_python() {
2420            return;
2421        }
2422        let dir = tempfile::tempdir().unwrap();
2423        let path = script(dir.path(), "fake.py", FAKE);
2424        let (server, _tools) = Server::start(
2425            &spec(&path, 1),
2426            dir.path(),
2427            dir.path(),
2428            DEFAULT_TEST_TIMEOUT,
2429            &Secrets::new(),
2430        )
2431        .expect("the fake server starts");
2432
2433        let started = std::time::Instant::now();
2434        let err = server
2435            .call_tool("echo_text", &json!({"text": "x", "sleep": true}))
2436            .unwrap_err();
2437        assert!(
2438            err.contains("did not answer") && err.contains("1s"),
2439            "the timeout names itself: {err}"
2440        );
2441        assert!(
2442            started.elapsed() < Duration::from_secs(5),
2443            "a hung call returns at the timeout, not when the server wakes up"
2444        );
2445
2446        // The poisoned connection was killed, so this is a new process talking to the same server.
2447        let out = server
2448            .call_tool("echo_text", &json!({"text": "after"}))
2449            .unwrap();
2450        assert_eq!(out, "echo: after");
2451    }
2452
2453    #[test]
2454    fn a_server_that_dies_is_an_error_with_its_own_stderr() {
2455        if !have_python() {
2456            return;
2457        }
2458        let dir = tempfile::tempdir().unwrap();
2459        let path = script(dir.path(), "dies.py", DIES);
2460        let err = Server::start(
2461            &spec(&path, 5),
2462            dir.path(),
2463            dir.path(),
2464            DEFAULT_TEST_TIMEOUT,
2465            &Secrets::new(),
2466        )
2467        .expect_err("a server that exits during the handshake cannot be used");
2468        assert!(
2469            err.contains("could not open the database"),
2470            "the server's own complaint is the error, not a timeout: {err}"
2471        );
2472    }
2473
2474    #[test]
2475    fn a_policy_override_can_allow_one_tool_and_leave_the_rest_asking() {
2476        let dir = tempfile::tempdir().unwrap();
2477        let mut s = spec(Path::new("/bin/true"), 5);
2478        s.policies.insert("read_text_file".into(), Policy::Allow);
2479        // No server is started here: the policy is manifest data, and asking for it should not
2480        // need a process.
2481        let (server, _) = (
2482            Arc::new(Server {
2483                spec: s.clone(),
2484                plugin_dir: dir.path().to_path_buf(),
2485                workspace: dir.path().to_path_buf(),
2486                timeout: Duration::from_secs(5),
2487                secrets: Secrets::new(),
2488                next_id: AtomicI64::new(1),
2489                state: Mutex::new(None),
2490                handshake: Mutex::new(None),
2491                stderr: Arc::new(Mutex::new(String::new())),
2492            }),
2493            (),
2494        );
2495        assert_eq!(server.policy_for("read_text_file"), Policy::Allow);
2496        assert_eq!(server.policy_for("write_file"), Policy::Ask);
2497    }
2498
2499    #[test]
2500    fn a_cancelled_run_stops_waiting_for_a_server() {
2501        // The fake hangs a call for 30 s. A cancelled run cannot interrupt a blocking read, but it
2502        // must stop *waiting*: the answer has nowhere to go, and the next call starts a fresh server
2503        // anyway.
2504        if !have_python() {
2505            return;
2506        }
2507        let dir = tempfile::tempdir().unwrap();
2508        let path = script(dir.path(), "fake.py", FAKE);
2509        let (server, _tools) = Server::start(
2510            &spec(&path, 60),
2511            dir.path(),
2512            dir.path(),
2513            DEFAULT_TEST_TIMEOUT,
2514            &Secrets::new(),
2515        )
2516        .expect("the fake server starts");
2517        let cancel = crate::cancel::Cancel::new();
2518        let flag = cancel.clone();
2519        let canceller = std::thread::spawn(move || {
2520            std::thread::sleep(Duration::from_millis(150));
2521            flag.cancel();
2522        });
2523        let started = std::time::Instant::now();
2524        let err = server
2525            .call_tool_unless("echo_text", &json!({"text": "x", "sleep": true}), &cancel)
2526            .unwrap_err();
2527        canceller.join().unwrap();
2528        assert!(err.contains("cancelled"), "the reason is the cancel: {err}");
2529        assert!(
2530            started.elapsed() < Duration::from_secs(5),
2531            "the wait ended at the cancel, not at the 60 s timeout: {:.2}s",
2532            started.elapsed().as_secs_f32()
2533        );
2534        // A server stopped for a cancel is a server stopped: the next call starts another one.
2535        let out = server
2536            .call_tool("echo_text", &json!({"text": "after"}))
2537            .unwrap();
2538        assert_eq!(out, "echo: after");
2539    }
2540
2541    #[test]
2542    fn a_result_that_is_not_text_says_so_instead_of_disappearing() {
2543        let text = content_text(&json!({"content": [
2544            {"type": "text", "text": "a"},
2545            {"type": "image", "data": "…"},
2546            {"type": "text", "text": "b"}
2547        ]}));
2548        assert_eq!(
2549            text,
2550            "a\n[image content from an MCP server is not shown]\nb"
2551        );
2552    }
2553}