From 76d57a549cfbab5dcaceea0747d4b3e5b06d04b0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 14 Oct 2026 15:51:13 +0200 Subject: [PATCH] feat(control): MCP hub (stdio + Streamable HTTP), config keys and GET /mcp Port of serve/mcp.py: server config validation, background start, paged tools/list, __ namespacing, error-as-text results with the character cap, restart on demand, cancellation, GET /mcp. Tested against the Original's fake MCP server. The server-side tool loop is intentionally not ported (documented). Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/app.rs | 4 + control-plane/src/config.rs | 37 + control-plane/src/lib.rs | 2 + control-plane/src/main.rs | 13 + control-plane/src/mcp.rs | 1518 +++++++++++++++++++++++++++++++ control-plane/src/responses.rs | 14 +- control-plane/src/server_api.rs | 9 + control-plane/tests/mcp_hub.rs | 444 +++++++++ docs/api-contract.md | 10 + 9 files changed, 2048 insertions(+), 3 deletions(-) create mode 100644 control-plane/src/mcp.rs create mode 100644 control-plane/tests/mcp_hub.rs diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs index aa5f7ec6..1e2e1704 100644 --- a/control-plane/src/app.rs +++ b/control-plane/src/app.rs @@ -39,6 +39,8 @@ pub struct AppState { pub started_at: std::time::SystemTime, /// Source of the model's chat template, served by `/props`. pub chat_template: Option>, + /// The MCP servers configured for the operator (`GET /mcp`). + pub mcp: Option>, } impl Default for AppState { @@ -59,6 +61,7 @@ impl Default for AppState { control: None, started_at: std::time::SystemTime::now(), chat_template: None, + mcp: None, } } } @@ -89,6 +92,7 @@ pub fn router(state: AppState) -> Router { .route("/props", get(crate::server_api::props)) .route("/slots", get(crate::server_api::slots)) .route("/v1/status", get(crate::server_api::v1_status)) + .route("/mcp", get(crate::server_api::mcp_status)) .route( "/settings", get(crate::server_api::settings_get).post(crate::server_api::settings_post), diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs index b288fa3e..57570739 100644 --- a/control-plane/src/config.rs +++ b/control-plane/src/config.rs @@ -42,6 +42,10 @@ pub struct Config { pub shared_settings_file: Option, /// Unload the engine after this long without requests (`engine.idle_unload_s`). pub idle_unload: Option, + /// MCP servers (`mcp_servers`, `mcpServers`, `mcp_config_file`); empty when there are none. + pub mcp_servers: std::collections::BTreeMap>, + /// The `mcp` block: timeouts and caps. + pub mcp_settings: crate::mcp::Settings, } #[derive(Default, Deserialize)] @@ -69,6 +73,11 @@ struct FileConfig { sampling: Option, reasoning_budget_tokens: Option, shared_settings_file: Option, + mcp_servers: Option, + #[serde(rename = "mcpServers")] + mcp_servers_desktop: Option, + mcp_config_file: Option, + mcp: Option, } #[derive(Deserialize)] @@ -481,7 +490,35 @@ impl Config { .as_deref() .map(crate::settings::default_shared_path) }); + let mut mcp_servers = std::collections::BTreeMap::new(); + let null = serde_json::Value::Null; + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers.as_ref().unwrap_or(&null), + "config mcp_servers", + )?); + mcp_servers.extend(crate::mcp::servers_from( + file.mcp_servers_desktop.as_ref().unwrap_or(&null), + "config mcpServers", + )?); + if let Some(path) = &file.mcp_config_file { + // Claude Desktop's format; a name in both takes this file's entry. + let location = format!("mcp_config_file {}", path.display()); + let text = std::fs::read_to_string(path) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let data: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')) + .map_err(|error| format!("[strata] {location}: {error}"))?; + let block = data + .get("mcpServers") + .or_else(|| data.get("mcp_servers")) + .ok_or_else(|| { + format!("[strata] {location}: expected {{\"mcpServers\": {{...}}}}") + })?; + mcp_servers.extend(crate::mcp::servers_from(block, &location)?); + } + let mcp_settings = crate::mcp::settings_from(file.mcp.as_ref().unwrap_or(&null))?; Ok(Self { + mcp_servers, + mcp_settings, aliases, cors_origins, trusted_origins, diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index e6379064..6e55a7d1 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -66,3 +66,5 @@ pub mod sampling; pub mod server_api; pub mod settings; + +pub mod mcp; diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 4b3d5489..e5691c29 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -841,6 +841,15 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box) -> Result<(), Box) -> Result<(), Box__`, called +//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`. +//! +//! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers` +//! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`, +//! `env`, `cwd`; newline-delimited JSON-RPC 2.0 on its stdin/stdout) or an address (`url`, +//! `headers`; Streamable HTTP, answered as JSON or as an event stream). No MCP SDK is needed. +//! +//! A server that does not start is left out with one log line; one that stops later is started +//! again by its next call (a failed start is retried at most every 10 s). Results reach the model +//! as text capped at `max_result_chars`; a failed call becomes a result starting with `error:` so +//! the model can react. +//! +//! Scope in this server: the hub, its configuration, tool listing and `GET /mcp` status. The +//! Original's chat loop that runs these tools *server-side* inside one chat completion +//! (`run_with_mcp`, `strata_mcp: true`) serves its bundled web page; Responses, Chat Completions and +//! Messages here return tool calls to the client, which executes them (the contract validated in +//! `docs/api-contract.md`), so the loop is deliberately not connected and no endpoint executes MCP +//! tools on a client's behalf. + +use std::{ + collections::{BTreeMap, HashMap, VecDeque}, + process::Stdio, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, + }, + time::{Duration, Instant}, +}; + +use serde_json::{Map, Value, json}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + process::{Child, ChildStdin, Command}, + sync::{Mutex as AsyncMutex, oneshot, watch}, +}; + +pub const PROTOCOL: &str = "2025-06-18"; + +/// `DEFAULTS` of the Original: the knobs of the optional `mcp` config block. +#[derive(Clone, Debug, PartialEq)] +pub struct Settings { + pub timeout_s: f64, + pub max_result_chars: usize, + pub max_rounds: usize, + pub start_timeout_s: f64, +} + +impl Default for Settings { + fn default() -> Self { + Self { + timeout_s: 60.0, + max_result_chars: 20_000, + max_rounds: 8, + start_timeout_s: 120.0, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum McpError { + /// A server answered with an error, stopped, or could not be reached. + Failed(String), + Timeout(String), + /// The chat was stopped while the call ran. + Cancelled, +} + +impl std::fmt::Display for McpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Failed(m) | Self::Timeout(m) => f.write_str(m), + Self::Cancelled => f.write_str("stopped"), + } + } +} + +fn failed(message: impl Into) -> McpError { + McpError::Failed(message.into()) +} + +pub type Cancel = watch::Receiver; + +/// A response `result`, or the error a JSON-RPC response carried (`_wait` of the Original). +fn response_result(message: &Value) -> Result { + if let Some(error) = message.get("error") { + let (text, code) = match error { + Value::Object(object) => ( + object + .get("message") + .and_then(Value::as_str) + .filter(|t| !t.is_empty()) + .unwrap_or("error") + .to_owned(), + object.get("code").cloned().unwrap_or(Value::Null), + ), + other => (other.to_string(), Value::Null), + }; + let code = if code.is_null() { + "None".to_owned() + } else { + code.to_string() + }; + return Err(failed(format!("{text} (code {code})"))); + } + Ok(message + .get("result") + .filter(|v| !v.is_null()) + .cloned() + .unwrap_or_else(|| json!({}))) +} + +type Slot = oneshot::Sender>; + +// ------------------------------------------------------------------------------------------------ stdio + +struct StdioTransport { + name: String, + stdin: Arc>>, + child: AsyncMutex>, + pid: Option, + pending: Arc>>, + next_id: AtomicU64, + stderr: Arc>>, + ended: Arc, +} + +impl StdioTransport { + async fn spawn(name: &str, config: &Map) -> Result { + let command = config + .get("command") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let mut process = Command::new(&command); + process + .args( + config + .get("args") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|a| a.as_str().map_or_else(|| a.to_string(), str::to_owned)), + ) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + for (key, value) in config + .get("env") + .and_then(Value::as_object) + .into_iter() + .flatten() + { + process.env( + key, + value + .as_str() + .map_or_else(|| value.to_string(), str::to_owned), + ); + } + if let Some(dir) = config + .get("cwd") + .and_then(Value::as_str) + .filter(|d| !d.is_empty()) + { + process.current_dir(dir); + } + #[cfg(unix)] + process.process_group(0); // its own group, so closing it ends its children too + let mut child = process + .spawn() + .map_err(|error| failed(format!("could not start {command:?}: {error}")))?; + let stdin = child.stdin.take(); + let stdout = child.stdout.take().expect("piped stdout"); + let stderr = child.stderr.take().expect("piped stderr"); + let pid = child.id(); + let pending: Arc>> = Arc::default(); + let log: Arc>> = Arc::default(); + let ended = Arc::new(std::sync::atomic::AtomicBool::new(false)); + + // The server's stderr is its log; the last lines explain a failure. + let (done_tx, done_rx) = oneshot::channel::<()>(); + { + let log = log.clone(); + let label = name.to_owned(); + tokio::spawn(async move { + let mut lines = BufReader::new(stderr).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let line = line.trim_end().to_owned(); + if line.is_empty() { + continue; + } + if std::env::var_os("STRATA_DEBUG").is_some() { + eprintln!("[mcp {label}] {line}"); + } + let mut log = log.lock().expect("mcp log"); + log.push_back(line); + if log.len() > 40 { + log.pop_front(); + } + } + let _ = done_tx.send(()); + }); + } + let stdin = Arc::new(AsyncMutex::new(stdin)); + let transport = Self { + name: name.to_owned(), + stdin: stdin.clone(), + child: AsyncMutex::new(Some(child)), + pid, + pending: pending.clone(), + next_id: AtomicU64::new(0), + stderr: log.clone(), + ended: ended.clone(), + }; + // Reader: one JSON-RPC message per line; requests from the server get "not supported". + let writer = stdin; + tokio::spawn(async move { + let mut lines = BufReader::new(stdout).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Ok(message) = serde_json::from_str::(line) else { + let mut log = log.lock().expect("mcp log"); + log.push_back(line.to_owned()); // a server that prints to stdout; the spec forbids it + continue; + }; + let batch = match message { + Value::Array(items) => items, + other => vec![other], + }; + for m in batch.into_iter().filter(Value::is_object) { + dispatch(&m, &pending, &writer).await; + } + } + ended.store(true, Ordering::SeqCst); + // Let the stderr reader take the last log line first (the pipe closes with the process). + let _ = tokio::time::timeout(Duration::from_secs(1), done_rx).await; + let tail = log + .lock() + .expect("mcp log") + .back() + .map(|l| format!(": {}", l.chars().take(300).collect::())) + .unwrap_or_default(); + let error = failed(format!("the server stopped{tail}")); + let slots: Vec = pending + .lock() + .expect("mcp pending") + .drain() + .map(|(_, s)| s) + .collect(); + for slot in slots { + let _ = slot.send(Err(error.clone())); + } + }); + Ok(transport) + } + + fn tail(&self) -> String { + self.stderr + .lock() + .expect("mcp log") + .back() + .map(|l| format!(": {}", l.chars().take(300).collect::())) + .unwrap_or_default() + } + + fn alive(&self) -> bool { + !self.ended.load(Ordering::SeqCst) + } + + async fn send(&self, message: &Value) -> Result<(), McpError> { + let mut data = serde_json::to_vec(message).expect("json"); + data.push(b'\n'); + let mut stdin = self.stdin.lock().await; + let Some(pipe) = stdin.as_mut() else { + return Err(failed(format!("the server stopped{}", self.tail()))); + }; + if pipe.write_all(&data).await.is_err() || pipe.flush().await.is_err() { + return Err(failed(format!("the server stopped{}", self.tail()))); + } + Ok(()) + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + mut cancel: Option, + ) -> Result { + if !self.alive() { + return Err(failed(format!("the server is not running{}", self.tail()))); + } + let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1; + let (slot, received) = oneshot::channel(); + self.pending.lock().expect("mcp pending").insert(id, slot); + if let Err(error) = self + .send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})) + .await + { + self.pending.lock().expect("mcp pending").remove(&id); + return Err(error); + } + let outcome = tokio::select! { + answer = received => match answer { + Ok(Ok(message)) => return response_result(&message), + Ok(Err(error)) => return Err(error), + Err(_) => return Err(failed(format!("the server stopped{}", self.tail()))), + }, + () = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))), + () = cancelled(&mut cancel) => McpError::Cancelled, + }; + self.pending.lock().expect("mcp pending").remove(&id); + // Tell the server to stop working on it. + let _ = self + .notify( + "notifications/cancelled", + Some(json!({"requestId": id, "reason": outcome.to_string()})), + ) + .await; + Err(outcome) + } + + async fn notify(&self, method: &str, params: Option) -> Result<(), McpError> { + let mut message = json!({"jsonrpc": "2.0", "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.send(&message).await + } + + /// As the spec says: close its stdin, give it a moment to exit, then end it and what it started. + async fn close(&self) { + self.stdin.lock().await.take(); + let child = self.child.lock().await.take(); + let Some(mut child) = child else { return }; + if tokio::time::timeout(Duration::from_secs(2), child.wait()) + .await + .is_err() + { + if let Some(pid) = self.pid { + let _ = Command::new("kill") + .args(["-TERM", &format!("-{pid}")]) + .stderr(Stdio::null()) + .status() + .await; + if tokio::time::timeout(Duration::from_secs(2), child.wait()) + .await + .is_err() + { + let _ = Command::new("kill") + .args(["-KILL", &format!("-{pid}")]) + .stderr(Stdio::null()) + .status() + .await; + } + } + let _ = child.start_kill(); + let _ = child.wait().await; + } + let _ = &self.name; + } +} + +/// A message from the server: answers go to the waiting call; its own requests get `ping` answered +/// and anything else "method not supported" (this client offers no client features); notifications +/// (log messages, list changes) are not used. +async fn dispatch( + message: &Value, + pending: &Arc>>, + writer: &Arc>>, +) { + if let Some(method) = message.get("method") { + if let Some(id) = message.get("id") { + let reply = if method == "ping" { + json!({"jsonrpc": "2.0", "id": id, "result": {}}) + } else { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, + "message": format!("method not supported: {}", method.as_str().unwrap_or(""))}}) + }; + // Written from its own task: the reader must never wait on a full pipe. + let writer = writer.clone(); + tokio::spawn(async move { + let mut data = serde_json::to_vec(&reply).expect("json"); + data.push(b'\n'); + if let Some(pipe) = writer.lock().await.as_mut() { + let _ = pipe.write_all(&data).await; + let _ = pipe.flush().await; + } + }); + } + return; + } + let slot = message + .get("id") + .and_then(Value::as_u64) + .and_then(|id| pending.lock().expect("mcp pending").remove(&id)); + if let Some(slot) = slot { + let _ = slot.send(Ok(message.clone())); + } // an answer to a call that timed out is simply dropped +} + +async fn cancelled(cancel: &mut Option) { + match cancel { + Some(receiver) => { + if *receiver.borrow() { + return; + } + while receiver.changed().await.is_ok() { + if *receiver.borrow() { + return; + } + } + std::future::pending::<()>().await; + } + None => std::future::pending::<()>().await, + } +} + +/// Python's `f"{x:g}"` for the timeouts in messages. +fn fmt_g(x: f64) -> String { + if x.fract() == 0.0 && x.abs() < 1e15 { + format!("{x:.0}") + } else { + let text = format!("{x:.6}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() + } +} + +// ------------------------------------------------------------------------------------------------ http + +struct Http { + url: String, + headers: Vec<(String, String)>, + client: reqwest::Client, + session: Mutex>, + protocol: Mutex>, + next_id: AtomicU64, + broken: Mutex>, +} + +impl Http { + fn new(config: &Map) -> Self { + let url = config + .get("url") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let headers = config + .get("headers") + .and_then(Value::as_object) + .into_iter() + .flatten() + .map(|(k, v)| { + ( + k.clone(), + v.as_str().map_or_else(|| v.to_string(), str::to_owned), + ) + }) + .collect(); + Self { + url, + headers, + client: reqwest::Client::new(), + session: Mutex::new(None), + protocol: Mutex::new(None), + next_id: AtomicU64::new(0), + broken: Mutex::new(None), + } + } + + fn alive(&self) -> bool { + self.broken.lock().expect("mcp http").is_none() + } + + fn builder(&self, method: reqwest::Method, timeout: Duration) -> reqwest::RequestBuilder { + let mut builder = self + .client + .request(method, &self.url) + .timeout(timeout) + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("User-Agent", "strata"); + for (key, value) in &self.headers { + builder = builder.header(key.as_str(), value.as_str()); + } + if let Some(session) = self.session.lock().expect("mcp http").clone() { + builder = builder.header("Mcp-Session-Id", session); + } + if let Some(protocol) = self.protocol.lock().expect("mcp http").clone() { + builder = builder.header("MCP-Protocol-Version", protocol); + } + builder + } + + /// POST one message; for a request (`id` set) return the response that answers it. + async fn post( + &self, + message: &Value, + id: Option, + timeout: Duration, + ) -> Result, McpError> { + let response = self + .builder(reqwest::Method::POST, timeout) + .body(serde_json::to_vec(message).expect("json")) + .send() + .await + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + if let Some(session) = response + .headers() + .get("Mcp-Session-Id") + .and_then(|v| v.to_str().ok()) + { + *self.session.lock().expect("mcp http") = Some(session.to_owned()); + } + let status = response.status(); + if !status.is_success() { + let had_session = self.session.lock().expect("mcp http").is_some(); + let detail: String = response + .text() + .await + .unwrap_or_default() + .chars() + .take(300) + .collect(); + if status.as_u16() == 404 && had_session { + // The session expired: a restart starts a new one. + *self.broken.lock().expect("mcp http") = + Some(failed("the server ended the session")); + } + return Err(failed(format!( + "HTTP {} {}{}", + status.as_u16(), + status.canonical_reason().unwrap_or(""), + if detail.is_empty() { + String::new() + } else { + format!(": {detail}") + } + ))); + } + let Some(id) = id else { return Ok(None) }; // a notification: 202, nothing to read + let is_events = response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.contains("text/event-stream")); + let found = if is_events { + read_events(response, id).await + } else { + let body = response + .text() + .await + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + if body.trim().is_empty() { + None + } else { + let parsed: Value = serde_json::from_str(&body) + .map_err(|error| failed(format!("could not reach {}: {error}", self.url)))?; + match parsed { + Value::Array(items) => items, + other => vec![other], + } + .into_iter() + .find(|m| { + m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none() + }) + } + }; + found + .map(Some) + .ok_or_else(|| failed("the server's answer did not contain a response")) + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + mut cancel: Option, + ) -> Result { + if let Some(error) = self.broken.lock().expect("mcp http").clone() { + return Err(error); + } + let id = self.next_id.fetch_add(1, Ordering::SeqCst) + 1; + let message = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + let outcome = tokio::select! { + answer = self.post(&message, Some(id), timeout + Duration::from_secs(5)) => { + return match answer { + Ok(Some(message)) => response_result(&message), + Ok(None) => Err(failed("the server's answer did not contain a response")), + Err(error) => Err(error), + }; + } + () = tokio::time::sleep(timeout) => McpError::Timeout(format!("{method} timed out after {} s", fmt_g(timeout.as_secs_f64()))), + () = cancelled(&mut cancel) => McpError::Cancelled, + }; + let _ = self + .notify( + "notifications/cancelled", + Some(json!({"requestId": id, "reason": outcome.to_string()})), + ) + .await; + Err(outcome) + } + + async fn notify(&self, method: &str, params: Option) -> Result<(), McpError> { + let mut message = json!({"jsonrpc": "2.0", "method": method}); + if let Some(params) = params { + message["params"] = params; + } + self.post(&message, None, Duration::from_secs(10)) + .await + .map(|_| ()) + } + + async fn close(&self) { + let Some(_) = self.session.lock().expect("mcp http").clone() else { + return; + }; + // End the session on the server (it may not allow that). + let _ = self + .builder(reqwest::Method::DELETE, Duration::from_secs(3)) + .send() + .await; + } +} + +/// Read an event stream until the event that answers `id` (it may carry notifications first). +async fn read_events(mut response: reqwest::Response, id: u64) -> Option { + let mut buffer = Vec::::new(); + let mut data: Vec = Vec::new(); + loop { + let chunk = response.chunk().await.ok().flatten(); + let finished = chunk.is_none(); + if let Some(chunk) = chunk { + buffer.extend_from_slice(&chunk); + } + while let Some(newline) = buffer.iter().position(|b| *b == b'\n') { + let raw: Vec = buffer.drain(..=newline).collect(); + let line = String::from_utf8_lossy(&raw) + .trim_end_matches(['\r', '\n']) + .to_owned(); + if let Some(rest) = line.strip_prefix("data:") { + data.push(rest.trim_start_matches(' ').to_owned()); + } else if line.is_empty() && !data.is_empty() { + let parsed = serde_json::from_str::(&data.join("\n")).ok(); + data.clear(); + let batch = match parsed { + Some(Value::Array(items)) => items, + Some(other) => vec![other], + None => Vec::new(), + }; + if let Some(found) = batch.into_iter().find(|m| { + m.get("id").and_then(Value::as_u64) == Some(id) && m.get("method").is_none() + }) { + return Some(found); + } + } + } + if finished { + return None; + } + } +} + +// ------------------------------------------------------------------------------------------------ one server + +type StartResult = + Result<(Arc, Vec, Map), (McpError, Option>)>; + +enum Transport { + Stdio(StdioTransport), + Http(Http), +} + +impl Transport { + fn alive(&self) -> bool { + match self { + Self::Stdio(t) => t.alive(), + Self::Http(t) => t.alive(), + } + } + + async fn request( + &self, + method: &str, + params: Value, + timeout: Duration, + cancel: Option, + ) -> Result { + match self { + Self::Stdio(t) => t.request(method, params, timeout, cancel).await, + Self::Http(t) => t.request(method, params, timeout, cancel).await, + } + } + + async fn notify(&self, method: &str) -> Result<(), McpError> { + match self { + Self::Stdio(t) => t.notify(method, None).await, + Self::Http(t) => t.notify(method, None).await, + } + } + + async fn close(&self) { + match self { + Self::Stdio(t) => t.close().await, + Self::Http(t) => t.close().await, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + Idle, + Starting, + Ready, + Failed, + Stopped, +} + +impl Status { + fn as_str(&self) -> &'static str { + match self { + Self::Idle => "idle", + Self::Starting => "starting", + Self::Ready => "ready", + Self::Failed => "failed", + Self::Stopped => "stopped", + } + } +} + +struct State { + status: Status, + error: Option, + tools: Vec, + info: Map, + transport: Option>, + last_start: Option, +} + +pub struct Server { + pub name: String, + config: Map, + kind: &'static str, + settings: Settings, + state: AsyncMutex, +} + +impl Server { + fn new(name: String, config: Map, settings: Settings) -> Self { + let kind = if config + .get("url") + .is_some_and(|u| u.as_str().is_some_and(|s| !s.is_empty())) + { + "http" + } else { + "stdio" + }; + Self { + name, + config, + kind, + settings, + state: AsyncMutex::new(State { + status: Status::Idle, + error: None, + tools: Vec::new(), + info: Map::new(), + transport: None, + last_start: None, + }), + } + } + + pub async fn start(&self) -> bool { + let mut state = self.state.lock().await; + self.start_locked(&mut state).await + } + + async fn start_locked(&self, state: &mut State) -> bool { + if let Some(old) = state.transport.take() { + old.close().await; + } + state.status = Status::Starting; + state.error = None; + state.last_start = Some(Instant::now()); + let timeout = Duration::from_secs_f64(self.settings.start_timeout_s); + let transport = if self.kind == "http" { + Ok(Transport::Http(Http::new(&self.config))) + } else { + StdioTransport::spawn(&self.name, &self.config) + .await + .map(Transport::Stdio) + }; + let result: StartResult = async { + let transport = Arc::new(transport.map_err(|e| (e, None))?); + let t = transport.clone(); + let fail = |e: McpError| (e, Some(t.clone())); + let init = transport + .request( + "initialize", + json!({"protocolVersion": PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "strata", "title": "Strata", "version": "1"}}), + timeout, + None, + ) + .await + .map_err(fail)?; + let protocol = init + .get("protocolVersion") + .and_then(Value::as_str) + .filter(|p| !p.is_empty()) + .unwrap_or(PROTOCOL) + .to_owned(); + if let Transport::Http(http) = &*transport { + *http.protocol.lock().expect("mcp http") = Some(protocol.clone()); + } + let mut info: Map = init + .get("serverInfo") + .and_then(Value::as_object) + .map(|o| { + o.iter() + .filter(|(k, _)| matches!(k.as_str(), "name" | "title" | "version")) + .map(|(k, v)| (k.clone(), v.clone())) + .collect() + }) + .unwrap_or_default(); + info.insert("protocol".into(), json!(protocol)); + transport.notify("notifications/initialized").await.map_err(fail)?; + let mut tools: Vec = Vec::new(); + let mut cursor: Option = None; + for _ in 0..100 { + // pages; a server that never stops paging is cut off + let params = cursor.as_ref().map_or_else(|| json!({}), |c| json!({"cursor": c})); + let page = match transport.request("tools/list", params, timeout, None).await { + Ok(page) => page, + // a server without tools (prompts/resources only) + Err(e) if e.to_string().contains("code -32601") && tools.is_empty() => break, + Err(e) => return Err(fail(e)), + }; + tools.extend( + page.get("tools") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|t| t.get("name").and_then(Value::as_str).is_some_and(|n| !n.is_empty())) + .cloned(), + ); + cursor = page + .get("nextCursor") + .and_then(Value::as_str) + .filter(|c| !c.is_empty()) + .map(str::to_owned); + if cursor.is_none() { + break; + } + } + Ok((transport, tools, info)) + } + .await; + match result { + Ok((transport, tools, info)) => { + let names = tools + .iter() + .take(8) + .filter_map(|t| t["name"].as_str()) + .collect::>() + .join(", ") + + if tools.len() > 8 { ", ..." } else { "" }; + eprintln!( + "MCP server {:?}: {} tool{}{}", + self.name, + tools.len(), + if tools.len() == 1 { "" } else { "s" }, + if tools.is_empty() { + String::new() + } else { + format!(" ({names})") + } + ); + state.tools = tools; + state.info = info; + state.transport = Some(transport); + state.status = Status::Ready; + true + } + Err((error, transport)) => { + state.status = Status::Failed; + state.error = Some(error.to_string()); + state.tools = Vec::new(); + if let Some(transport) = transport { + transport.close().await; + } + eprintln!( + "MCP server {:?} did not start: {error}. Its tools are left out; the chat works without them.", + self.name + ); + false + } + } + } + + pub async fn call( + &self, + tool: &str, + arguments: Value, + timeout: Duration, + cancel: Option, + ) -> Result { + let transport = { + let mut state = self.state.lock().await; + if state.transport.as_ref().is_none_or(|t| !t.alive()) { + // It stopped since its last call (a crash, an expired session): start it again; one + // that failed to start is retried at most every 10 s. + if state.status == Status::Failed + && state + .last_start + .is_some_and(|at| at.elapsed() < Duration::from_secs(10)) + { + return Err(failed(format!( + "the server is not running ({})", + state.error.clone().unwrap_or_else(|| "it stopped".into()) + ))); + } + eprintln!("MCP server {:?} had stopped; starting it again", self.name); + if !self.start_locked(&mut state).await { + return Err(failed(format!( + "the server could not be started again: {}", + state.error.clone().unwrap_or_default() + ))); + } + } + state.transport.clone().expect("started") + }; + let result = transport + .request( + "tools/call", + json!({"name": tool, "arguments": arguments}), + timeout, + cancel, + ) + .await; + if let Err(error) = &result + && !transport.alive() + { + let mut state = self.state.lock().await; + state.status = Status::Stopped; + state.error = Some(error.to_string()); + } + result + } + + pub async fn close(&self) { + let mut state = self.state.lock().await; + if let Some(transport) = state.transport.take() { + transport.close().await; + } + if matches!(state.status, Status::Ready | Status::Starting) { + state.status = Status::Stopped; + } + } +} + +// ------------------------------------------------------------------------------------------------ the hub + +/// `result_text`: an MCP tool result as the text the model reads - text blocks as they are, other +/// blocks named. +pub fn result_text(result: &Value) -> String { + let mut parts: Vec = Vec::new(); + for block in result + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let Some(block) = block.as_object() else { + continue; + }; + let text = |key: &str| { + block + .get(key) + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_owned)) + .unwrap_or_default() + }; + match block.get("type").and_then(Value::as_str) { + Some("text") => parts.push(text("text")), + Some("resource") => { + let resource = block.get("resource").and_then(Value::as_object); + parts.push(match resource.and_then(|r| r.get("text")) { + Some(v) => v.as_str().map_or_else(|| v.to_string(), str::to_owned), + None => format!( + "[resource {} ({}), not shown]", + resource + .and_then(|r| r.get("uri")) + .and_then(Value::as_str) + .unwrap_or(""), + resource + .and_then(|r| r.get("mimeType")) + .and_then(Value::as_str) + .unwrap_or("binary") + ), + }); + } + Some("resource_link") => parts.push( + format!("[resource link: {} {}]", text("name"), text("uri")).replace(" ", " "), + ), + Some(kind @ ("image" | "audio")) => { + let size = block + .get("data") + .and_then(Value::as_str) + .map_or(0, str::len) + * 3 + / 4; + parts.push(format!( + "[{kind} ({}, {} bytes): not shown to the model]", + block.get("mimeType").and_then(Value::as_str).unwrap_or("?"), + group_thousands(size) + )); + } + _ => parts.push(Value::Object(block.clone()).to_string()), + } + } + if parts.is_empty() + && let Some(structured) = result.get("structuredContent").filter(|v| !v.is_null()) + { + parts.push(structured.to_string()); + } + parts.join("\n") +} + +/// Python's `f"{n:,}"`. +fn group_thousands(n: usize) -> String { + let digits = n.to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +fn clean(name: &str) -> String { + let cleaned: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' || c == '-' { + c + } else { + '_' + } + }) + .collect(); + if cleaned.is_empty() { + "x".into() + } else { + cleaned + } +} + +/// One tool call's outcome (`McpHub.call`). +#[derive(Clone, Debug, PartialEq)] +pub struct CallOutput { + pub ok: bool, + /// What the model reads, capped. + pub text: String, + /// The full length in characters. + pub chars: usize, + pub truncated: bool, + pub ms: u64, + pub server: Option, + pub tool: String, +} + +pub struct Hub { + pub servers: Vec>, + settings: Settings, +} + +impl Hub { + pub fn new(servers: BTreeMap>, settings: Settings) -> Self { + Self { + servers: servers + .into_iter() + .map(|(name, config)| Arc::new(Server::new(name, config, settings.clone()))) + .collect(), + settings, + } + } + + /// Start every server concurrently and wait for all of them (npx may download a package first; + /// callers that must not wait spawn this). + pub async fn start(&self) { + let mut tasks = tokio::task::JoinSet::new(); + for server in &self.servers { + let server = server.clone(); + tasks.spawn(async move { server.start().await }); + } + while tasks.join_next().await.is_some() {} + } + + /// tool name the model sees -> (server, the tool's own name). A server that stopped after it + /// was ready keeps its tools here: a call starts it again. + pub async fn routes(&self) -> Vec<(String, Arc, String)> { + let mut out: Vec<(String, Arc, String)> = Vec::new(); + for server in &self.servers { + let state = server.state.lock().await; + if !matches!(state.status, Status::Ready | Status::Stopped) { + continue; + } + for tool in &state.tools { + let own = tool["name"].as_str().unwrap_or_default().to_owned(); + let mut name: String = format!("{}__{}", clean(&server.name), clean(&own)) + .chars() + .take(64) + .collect(); + let mut n = 2; + while out.iter().any(|(existing, _, _)| *existing == name) { + // two names that differ only in cleaned characters + name = format!("{}_{n}", name.chars().take(60).collect::()); + n += 1; + } + out.push((name, server.clone(), own)); + } + } + out + } + + /// The tools in the chat template's form (`{name, description, parameters}`); `exclude`: names + /// the request brought itself (those win). + pub async fn template_tools(&self, exclude: &[String]) -> Vec { + let mut out = Vec::new(); + for (name, server, own) in self.routes().await { + if exclude.contains(&name) { + continue; + } + let state = server.state.lock().await; + let Some(tool) = state.tools.iter().find(|t| t["name"] == own.as_str()) else { + continue; + }; + let schema = tool + .get("inputSchema") + .filter(|s| s.as_object().is_some_and(|o| !o.is_empty())) + .cloned() + .unwrap_or_else(|| json!({"type": "object", "properties": {}})); + let description = [tool.get("description"), tool.get("title")] + .into_iter() + .flatten() + .filter_map(Value::as_str) + .find(|s| !s.is_empty()) + .unwrap_or(""); + out.push(json!({"name": name, "description": description, "parameters": schema})); + } + out + } + + /// Run one tool. Errors become text starting with `error:`; only a stop (`cancel`) is an `Err`. + pub async fn call( + &self, + name: &str, + arguments: Value, + cancel: Option, + ) -> Result { + let started = Instant::now(); + let route = self.routes().await.into_iter().find(|(n, _, _)| n == name); + let (server, tool) = match &route { + Some((_, server, tool)) => (Some(server.clone()), tool.clone()), + None => (None, name.to_owned()), + }; + let (mut text, ok) = match &server { + None => (format!("error: there is no tool named {name:?}"), false), + Some(server) => { + let arguments = if arguments.is_object() { + arguments + } else { + json!({}) + }; + match server + .call( + &tool, + arguments, + Duration::from_secs_f64(self.settings.timeout_s), + cancel, + ) + .await + { + Ok(result) => { + let text = result_text(&result); + let ok = !result.get("isError").is_some_and(|v| v == &json!(true)); + if ok { + (text, true) + } else { + ( + format!( + "error: {}", + if text.is_empty() { + "the tool reported an error".to_owned() + } else { + text + } + ), + false, + ) + } + } + Err(McpError::Cancelled) => return Err(McpError::Cancelled), + Err(error) => (format!("error: {error}"), false), + } + } + }; + let cap = self.settings.max_result_chars; + let full = text.chars().count(); + let truncated = cap > 0 && full > cap; + if truncated { + text = text.chars().take(cap).collect::() + + &format!( + "\n\n[... truncated: the tool returned {} characters; only the first {} are shown]", + group_thousands(full), + group_thousands(cap) + ); + } + Ok(CallOutput { + ok, + text, + chars: full, + truncated, + ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + server: server.as_ref().map(|s| s.name.clone()), + tool, + }) + } + + /// `GET /mcp`: every server, its state and its tools. + pub async fn status(&self) -> Value { + let routes = self.routes().await; + let mut servers = Vec::new(); + for server in &self.servers { + let state = server.state.lock().await; + let tools: Vec = state + .tools + .iter() + .map(|tool| { + let own = tool["name"].as_str().unwrap_or_default(); + let seen = routes + .iter() + .find(|(_, s, t)| Arc::ptr_eq(s, server) && t == own) + .map_or(own, |(n, _, _)| n.as_str()); + json!({"name": seen, "tool": own, + "description": tool.get("description").and_then(Value::as_str).unwrap_or("") + .chars().take(300).collect::()}) + }) + .collect(); + servers.push(json!({"name": server.name, "transport": server.kind, + "status": state.status.as_str(), "error": state.error, "info": state.info, + "tools": tools})); + } + json!({"servers": servers, "tools": routes.len(), + "settings": {"timeout_s": self.settings.timeout_s, + "max_result_chars": self.settings.max_result_chars, + "max_rounds": self.settings.max_rounds}}) + } + + pub async fn close(&self) { + for server in &self.servers { + server.close().await; + } + } +} + +// ------------------------------------------------------------------------------------------------ config + +/// Python truthiness of a JSON value (`None`, `""`, `0`, `False`, `[]`, `{}`). +fn falsy(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Bool(b) => !b, + Value::Number(n) => n.as_f64() == Some(0.0), + Value::String(s) => s.is_empty(), + Value::Array(a) => a.is_empty(), + Value::Object(o) => o.is_empty(), + } +} + +fn check_server(name: &str, config: &Value, location: &str) -> Result, String> { + let Some(object) = config.as_object() else { + return Err(format!( + "[strata] {location}: MCP server {} must be an object with \"command\" or \"url\"", + leleka_serving_policy::shared::py_str_repr(name) + )); + }; + let quoted = leleka_serving_policy::shared::py_str_repr(name); + let truthy = |key: &str| object.get(key).is_some_and(|v| !falsy(v)); + if truthy("url") { + if object.get("type") == Some(&json!("sse")) { + return Err(format!( + "[strata] {location}: MCP server {quoted} uses the old SSE transport (\"type\": \"sse\"); Strata speaks Streamable HTTP - most servers offer it at /mcp" + )); + } + if object + .get("headers") + .is_some_and(|h| !falsy(h) && !h.is_object()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"headers\" must be an object" + )); + } + return Ok(object.clone()); + } + if object + .get("command") + .and_then(Value::as_str) + .is_none_or(|c| c.trim().is_empty()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted} needs \"command\" (a program to start) or \"url\"" + )); + } + if object + .get("args") + .is_some_and(|a| !falsy(a) && !a.is_array()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"args\" must be a list" + )); + } + if object + .get("env") + .is_some_and(|e| !falsy(e) && !e.is_object()) + { + return Err(format!( + "[strata] {location}: MCP server {quoted}: \"env\" must be an object" + )); + } + Ok(object.clone()) +} + +/// `{"name": {...}}` with the entries checked; `"disabled": true` leaves one out. +pub fn servers_from( + block: &Value, + location: &str, +) -> Result>, String> { + let mut out = BTreeMap::new(); + match block { + Value::Null => {} + Value::Object(map) => { + for (name, config) in map { + if config.get("disabled") == Some(&json!(true)) { + continue; + } + out.insert(name.clone(), check_server(name, config, location)?); + } + } + _ => { + return Err(format!( + "[strata] {location}: the MCP servers must be an object {{\"name\": {{...}}}}" + )); + } + } + Ok(out) +} + +/// The run config's optional `mcp` block: `timeout_s`, `max_result_chars`, `max_rounds`, +/// `start_timeout_s`. +pub fn settings_from(block: &Value) -> Result { + let mut settings = Settings::default(); + let Some(map) = block.as_object() else { + return Ok(settings); + }; + for (key, value) in map { + let number = value.is_number(); + let bad = |expected: &str| { + format!( + "[strata] config mcp.{key}={}: {expected}", + leleka_serving_policy::shared::py_repr(value) + ) + }; + match key.as_str() { + "timeout_s" | "start_timeout_s" => { + let seconds = value + .as_f64() + .filter(|v| number && *v > 0.0 && v.is_finite()) + .ok_or_else(|| bad("expected a number of seconds > 0"))?; + if key == "timeout_s" { + settings.timeout_s = seconds; + } else { + settings.start_timeout_s = seconds; + } + } + "max_result_chars" | "max_rounds" => { + let count = value + .as_u64() + .filter(|v| *v >= 1) + .or_else(|| { + value + .as_f64() + .filter(|f| f.fract() == 0.0 && *f >= 1.0) + .map(|f| f as u64) + }) + .ok_or_else(|| bad("expected a positive integer"))?; + if key == "max_result_chars" { + settings.max_result_chars = usize::try_from(count).unwrap_or(usize::MAX); + } else { + settings.max_rounds = usize::try_from(count).unwrap_or(usize::MAX); + } + } + other => eprintln!( + "config mcp.{other}={}: unknown key, ignored", + leleka_serving_policy::shared::py_repr(value) + ), + } + } + Ok(settings) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn results_read_as_text_with_other_blocks_named() { + let result = json!({"content": [ + {"type": "text", "text": "hello"}, + {"type": "resource", "resource": {"uri": "file:///a", "mimeType": "image/png"}}, + {"type": "resource", "resource": {"text": "inline"}}, + {"type": "resource_link", "name": "doc", "uri": "http://x"}, + {"type": "image", "mimeType": "image/png", "data": "AAAAAAAA"}, + {"type": "weird", "k": 1}, + "not a block" + ]}); + assert_eq!( + result_text(&result), + "hello\n[resource file:///a (image/png), not shown]\ninline\n[resource link: doc http://x]\n[image (image/png, 6 bytes): not shown to the model]\n{\"k\":1,\"type\":\"weird\"}" + ); + assert_eq!( + result_text(&json!({"structuredContent": {"a": 1}})), + "{\"a\":1}" + ); + assert_eq!(result_text(&json!({})), ""); + assert_eq!(group_thousands(1234567), "1,234,567"); + assert_eq!(group_thousands(12), "12"); + } + + #[test] + fn json_rpc_errors_read_like_the_originals() { + assert_eq!( + response_result(&json!({"error": {"code": -32602, "message": "unknown tool x"}})) + .unwrap_err(), + failed("unknown tool x (code -32602)") + ); + assert_eq!( + response_result(&json!({"error": "plain"})).unwrap_err(), + failed("\"plain\" (code None)") + ); + assert_eq!(response_result(&json!({"id": 1})).unwrap(), json!({})); + } + + #[test] + fn server_entries_are_checked_at_start() { + let ok = servers_from( + &json!({"a": {"command": "npx", "args": ["x"]}, "b": {"url": "http://h/mcp", "headers": {"k": "v"}}, + "off": {"command": "x", "disabled": true}}), + "config mcp_servers", + ) + .unwrap(); + assert_eq!(ok.keys().collect::>(), vec!["a", "b"]); + for bad in [ + json!({"a": "nope"}), + json!({"a": {}}), + json!({"a": {"command": " "}}), + json!({"a": {"command": "x", "args": "y"}}), + json!({"a": {"command": "x", "env": ["x"]}}), + json!({"a": {"url": "http://h", "type": "sse"}}), + json!({"a": {"url": "http://h", "headers": ["x"]}}), + json!([1]), + ] { + assert!(servers_from(&bad, "w").is_err(), "{bad}"); + } + assert!(servers_from(&Value::Null, "w").unwrap().is_empty()); + } + + #[test] + fn settings_block_is_checked() { + let s = settings_from(&json!({"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3, "start_timeout_s": 7.5, "x": 1})).unwrap(); + assert_eq!( + s, + Settings { + timeout_s: 5.0, + max_result_chars: 100, + max_rounds: 3, + start_timeout_s: 7.5 + } + ); + for bad in [ + json!({"timeout_s": 0}), + json!({"timeout_s": "5"}), + json!({"max_rounds": 0}), + json!({"max_result_chars": 1.5}), + ] { + assert!(settings_from(&bad).is_err(), "{bad}"); + } + assert_eq!(settings_from(&Value::Null).unwrap(), Settings::default()); + } + + #[test] + fn tool_names_are_cleaned_and_made_unique() { + assert_eq!(clean("my server!"), "my_server_"); + assert_eq!(clean(""), "x"); + assert_eq!(fmt_g(60.0), "60"); + assert_eq!(fmt_g(0.5), "0.5"); + } +} diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index d2540c98..2ea0dfcf 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -4394,7 +4394,11 @@ mod tests { let plan = generate.unwrap().reasoning.expect("a plan"); assert_eq!(plan.budget, 20); assert!(!plan.wrap_up.is_empty()); - assert_eq!(plan.stop_ids, vec![257], "<|im_end|> of the test vocabulary"); + assert_eq!( + plan.stop_ids, + vec![257], + "<|im_end|> of the test vocabulary" + ); assert_eq!((plan.token_bytes)(79), b"O".to_vec()); // Thinking off, a zero budget, or no budget at all: no plan. for body in [ @@ -4413,8 +4417,12 @@ mod tests { let (_, generate) = captured_generate(settings, thinking(json!({})), create).await; assert_eq!(generate.unwrap().reasoning.unwrap().budget, 50); let settings = crate::settings::Settings::default().with_reasoning_budget(Some(json!(50))); - let (_, generate) = - captured_generate(settings, thinking(json!({"reasoning_budget_tokens": 0})), create).await; + let (_, generate) = captured_generate( + settings, + thinking(json!({"reasoning_budget_tokens": 0})), + create, + ) + .await; assert!(generate.unwrap().reasoning.is_none()); } diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index b497d6f4..2214e2e3 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -531,3 +531,12 @@ pub async fn cors_layer(State(cors): State>, request: Request, next: N } response } + +/// `GET /mcp`: the configured MCP servers, their state and tools (empty when there are none). +pub async fn mcp_status(State(state): State) -> Response { + let body = match &state.mcp { + Some(hub) => hub.status().await, + None => json!({"servers": [], "tools": 0}), + }; + reply(StatusCode::OK, body) +} diff --git a/control-plane/tests/mcp_hub.rs b/control-plane/tests/mcp_hub.rs new file mode 100644 index 00000000..25ef696f --- /dev/null +++ b/control-plane/tests/mcp_hub.rs @@ -0,0 +1,444 @@ +//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`, +//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients, +//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation. +//! The tests are skipped (with a message) when `python3` is not installed. + +use std::{ + collections::BTreeMap, + io::{BufRead, BufReader}, + path::PathBuf, + process::{Child, Command, Stdio}, +}; + +use serde_json::{Map, Value, json}; +use strata_control::mcp::{Hub, McpError, Settings, servers_from, settings_from}; +use tokio::sync::watch; + +fn fake_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py") +} + +fn python() -> Option<&'static str> { + Command::new("python3") + .arg("--version") + .stdout(Stdio::null()) + .status() + .ok() + .filter(|s| s.success()) + .map(|_| "python3") +} + +fn stdio(args: &[&str], log: Option<&PathBuf>) -> Map { + let mut all = vec![fake_path().to_string_lossy().into_owned()]; + all.extend(args.iter().map(|a| (*a).to_owned())); + let mut config = json!({"command": "python3", "args": all}); + if let Some(log) = log { + config["env"] = json!({"FAKE_MCP_LOG": log}); + } + config.as_object().unwrap().clone() +} + +fn hub(servers: Vec<(&str, Map)>, settings: Settings) -> Hub { + Hub::new( + servers + .into_iter() + .map(|(n, c)| (n.to_owned(), c)) + .collect::>(), + settings, + ) +} + +fn names(status: &Value, server: &str) -> Vec { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == server) + .unwrap()["tools"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_owned()) + .collect() +} + +const TOOLS: [&str; 6] = ["echo", "fail", "sleep", "big", "die", "add"]; + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn stdio_servers_list_call_and_fail_like_the_python_hub() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let log = std::env::temp_dir().join(format!("strata-mcp-{}.jsonl", std::process::id())); + let _ = std::fs::remove_file(&log); + let settings = Settings { + timeout_s: 1.5, + max_result_chars: 1000, + ..Settings::default() + }; + let hub = hub( + vec![ + ("fake", stdio(&[], Some(&log))), + ("paged", stdio(&["--page", "4"], None)), + ("broken", stdio(&["--crash-at-start"], None)), + ( + "missing", + json!({"command": "strata-no-such-program"}) + .as_object() + .unwrap() + .clone(), + ), + ], + settings, + ); + hub.start().await; + let status = hub.status().await; + let by_name = |n: &str| -> Value { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == n) + .unwrap() + .clone() + }; + + // initialize + tools/list over every page + assert_eq!(by_name("fake")["status"], "ready"); + assert_eq!(by_name("fake")["transport"], "stdio"); + assert_eq!(by_name("fake")["info"]["name"], "fake"); + assert_eq!(by_name("fake")["info"]["protocol"], "2025-06-18"); + let want: Vec = TOOLS.iter().map(|t| format!("fake__{t}")).collect(); + assert_eq!(names(&status, "fake"), want); + assert_eq!( + names(&status, "paged"), + TOOLS + .iter() + .map(|t| format!("paged__{t}")) + .collect::>() + ); + assert_eq!(status["tools"], 12); + assert_eq!(status["settings"]["max_result_chars"], 1000); + + // servers that do not start are left out, with the reason + assert_eq!(by_name("broken")["status"], "failed"); + assert!( + by_name("broken")["error"] + .as_str() + .unwrap() + .contains("missing configuration"), + "{}", + by_name("broken") + ); + assert_eq!(by_name("missing")["status"], "failed"); + assert!( + by_name("missing")["error"] + .as_str() + .unwrap() + .contains("could not start") + ); + + // the tools in the chat template's form + let tools = hub.template_tools(&["paged__echo".to_owned()]).await; + let echo = tools.iter().find(|t| t["name"] == "fake__echo").unwrap(); + assert_eq!(echo["parameters"]["properties"]["text"]["type"], "string"); + assert_eq!(echo["description"], "Returns the text it is given."); + assert!(tools.iter().all(|t| t["name"] != "paged__echo")); + assert_eq!(tools.len(), 11); + + // calls + let r = hub + .call("fake__echo", json!({"text": "hello wörld"}), None) + .await + .unwrap(); + assert_eq!( + (r.ok, r.text.as_str(), r.server.as_deref(), r.tool.as_str()), + (true, "hello wörld", Some("fake"), "echo") + ); + assert_eq!( + hub.call("fake__add", json!({"a": 2, "b": 40}), None) + .await + .unwrap() + .text, + "42" + ); + let r = hub.call("fake__fail", json!({}), None).await.unwrap(); + assert!(!r.ok); + assert_eq!(r.text, "error: it failed on purpose"); + let r = hub.call("nobody__nothing", json!({}), None).await.unwrap(); + assert!( + !r.ok && r.text.starts_with("error: there is no tool"), + "{}", + r.text + ); + // arguments that are not an object are sent as {} + assert_eq!( + hub.call("fake__echo", json!("x"), None).await.unwrap().text, + "" + ); + // a JSON-RPC error from the server + let fake = hub.servers.iter().find(|s| s.name == "fake").unwrap(); + let error = fake + .call( + "no-such-tool", + json!({}), + std::time::Duration::from_secs(5), + None, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("unknown tool"), "{error}"); + + // a call that outlasts the timeout, then the server still answers + let started = std::time::Instant::now(); + let r = hub + .call("fake__sleep", json!({"seconds": 5}), None) + .await + .unwrap(); + assert!(started.elapsed().as_secs_f64() < 4.0); + assert!(!r.ok); + assert!(r.text.contains("timed out after 1.5 s"), "{}", r.text); + assert_eq!( + hub.call("fake__echo", json!({"text": "still here"}), None) + .await + .unwrap() + .text, + "still here" + ); + + // the result cap + let r = hub + .call("fake__big", json!({"n": 50000}), None) + .await + .unwrap(); + assert!(r.ok && r.truncated); + assert_eq!(r.chars, 50000); + assert!( + r.text + .starts_with(&format!("{}\n\n[... truncated", "y".repeat(1000))) + ); + assert!(r.text.contains("50,000 characters")); + assert!(r.text.chars().count() < 1200); + + // cancellation reaches the server as notifications/cancelled + let (stop, cancel) = watch::channel(false); + let canceller = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let _ = stop.send(true); + }); + let started = std::time::Instant::now(); + let outcome = hub + .call("fake__sleep", json!({"seconds": 1.2}), Some(cancel)) + .await; + assert_eq!(outcome.unwrap_err(), McpError::Cancelled); + assert!(started.elapsed().as_secs_f64() < 1.0); + canceller.await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(400)).await; + let seen = std::fs::read_to_string(&log).unwrap(); + assert!(seen.contains("\"cancelled\""), "{seen}"); + + hub.close().await; + let _ = std::fs::remove_file(&log); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_server_that_dies_mid_call_is_started_again_by_the_next_call() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let hub = hub( + vec![("solo", stdio(&[], None))], + Settings { + timeout_s: 5.0, + ..Settings::default() + }, + ); + hub.start().await; + let r = hub.call("solo__die", json!({}), None).await.unwrap(); + assert!(!r.ok); + assert!(r.text.contains("the server stopped"), "{}", r.text); + assert!(r.text.contains("dying on purpose"), "{}", r.text); + let status = hub.status().await; + assert_eq!(status["servers"][0]["status"], "stopped"); + assert_eq!( + status["tools"], 6, + "its tools stay: the next call restarts it" + ); + let r = hub + .call("solo__echo", json!({"text": "back"}), None) + .await + .unwrap(); + assert_eq!(r.text, "back"); + assert_eq!(hub.status().await["servers"][0]["status"], "ready"); + hub.close().await; +} + +struct HttpFake(Child); + +impl HttpFake { + fn start(port: u16) -> Self { + let mut child = Command::new("python3") + .arg(fake_path()) + .args(["--http", &port.to_string()]) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut line = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + assert!(line.contains("listening"), "{line}"); + Self(child) + } +} + +impl Drop for HttpFake { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn streamable_http_servers_answer_as_json_or_as_an_event_stream() { + if python().is_none() { + eprintln!("python3 not found: skipped"); + return; + } + let port = { + let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + probe.local_addr().unwrap().port() + }; + let _server = HttpFake::start(port); + let hub = + hub( + vec![ + ( + "web", + json!({"url": format!("http://127.0.0.1:{port}/mcp"), "headers": {"X-Test": "1"}}) + .as_object() + .unwrap() + .clone(), + ), + ( + "down", + json!({"url": "http://127.0.0.1:9/mcp"}).as_object().unwrap().clone(), + ), + ], + Settings { + timeout_s: 1.5, + ..Settings::default() + }, + ); + hub.start().await; + let status = hub.status().await; + let server = |n: &str, status: &Value| -> Value { + status["servers"] + .as_array() + .unwrap() + .iter() + .find(|s| s["name"] == n) + .unwrap() + .clone() + }; + assert_eq!(server("web", &status)["transport"], "http"); + assert_eq!(server("web", &status)["status"], "ready", "{status}"); + assert_eq!(names(&status, "web").len(), 6); // paged, with the session id on every request + // tools/call answers as an event stream with a progress notification first + assert_eq!( + hub.call("web__echo", json!({"text": "over http"}), None) + .await + .unwrap() + .text, + "over http" + ); + assert_eq!( + hub.call("web__fail", json!({}), None).await.unwrap().text, + "error: it failed on purpose" + ); + let r = hub + .call("web__sleep", json!({"seconds": 4}), None) + .await + .unwrap(); + assert!(r.text.contains("timed out"), "{}", r.text); + let down = server("down", &hub.status().await); + assert_eq!(down["status"], "failed"); + assert!(down["error"].as_str().unwrap().contains("could not reach")); + hub.close().await; +} + +#[test] +fn config_accepts_both_spellings_and_checks_every_entry() { + let both = servers_from( + &json!({"a": {"command": "x"}, "off": {"url": "http://h/mcp", "disabled": true}}), + "config mcp_servers", + ) + .unwrap(); + assert_eq!(both.keys().collect::>(), ["a"]); + for (bad, why) in [ + (json!({"a": {}}), "needs \"command\""), + ( + json!({"a": {"command": "x", "args": "y"}}), + "\"args\" must be a list", + ), + ( + json!({"a": {"url": "http://h", "type": "sse"}}), + "old SSE transport", + ), + ( + json!({"a": {"url": "http://h", "headers": ["x"]}}), + "\"headers\" must be an object", + ), + ] { + let error = servers_from(&bad, "config mcpServers").unwrap_err(); + assert!(error.contains(why), "{error}"); + assert!( + error.starts_with("[strata] config mcpServers: MCP server 'a'"), + "{error}" + ); + } + assert!( + settings_from(&json!({"max_rounds": 0})) + .unwrap_err() + .contains("positive integer") + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn get_mcp_reports_the_hub_or_an_empty_list() { + use std::sync::Arc; + use strata_control::app::{AppState, router}; + + async fn get(state: AppState) -> Value { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/mcp", listener.local_addr().unwrap()); + let app = router(state); + let server = tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let text = reqwest::get(url).await.unwrap().text().await.unwrap(); + let answer: Value = serde_json::from_str(&text).unwrap(); + server.abort(); + answer + } + assert_eq!( + get(AppState::default()).await, + json!({"servers": [], "tools": 0}) + ); + let hub = Arc::new(hub( + vec![("broken", stdio(&["--crash-at-start"], None))], + Settings::default(), + )); + hub.start().await; + let state = AppState { + mcp: Some(hub.clone()), + ..Default::default() + }; + let answer = get(state).await; + assert_eq!(answer["servers"][0]["status"], "failed"); + assert_eq!(answer["tools"], 0); + assert_eq!(answer["settings"]["max_rounds"], 8); + hub.close().await; +} diff --git a/docs/api-contract.md b/docs/api-contract.md index db29d859..cde97280 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -199,6 +199,16 @@ Ported from `engine/strata/serve/server.py` and replayed against the real Python authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`; - engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request ends the engine, fails the request with a clear error and uses the restart budget. +- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in + `control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file` + and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are + validated at start; stdio and Streamable HTTP servers start in the background, tools are listed + (all pages) and namespaced `__`, a server that stopped is started again by its next + call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call + sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools + (`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop + (`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return + tool calls to the client, so no endpoint executes MCP tools on a client's behalf. Differences from the Python server: authentication is Bearer on every path except `/health` and `/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and