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, <server>__<tool> 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 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:51:13 +02:00
co-authored by Claude Sonnet 5.5
parent 2c7fcf4af1
commit 76d57a549c
9 changed files with 2048 additions and 3 deletions
+4
View File
@@ -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<Arc<str>>,
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<Arc<crate::mcp::Hub>>,
}
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),
+37
View File
@@ -42,6 +42,10 @@ pub struct Config {
pub shared_settings_file: Option<PathBuf>,
/// Unload the engine after this long without requests (`engine.idle_unload_s`).
pub idle_unload: Option<Duration>,
/// MCP servers (`mcp_servers`, `mcpServers`, `mcp_config_file`); empty when there are none.
pub mcp_servers: std::collections::BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
/// The `mcp` block: timeouts and caps.
pub mcp_settings: crate::mcp::Settings,
}
#[derive(Default, Deserialize)]
@@ -69,6 +73,11 @@ struct FileConfig {
sampling: Option<serde_json::Value>,
reasoning_budget_tokens: Option<serde_json::Value>,
shared_settings_file: Option<PathBuf>,
mcp_servers: Option<serde_json::Value>,
#[serde(rename = "mcpServers")]
mcp_servers_desktop: Option<serde_json::Value>,
mcp_config_file: Option<PathBuf>,
mcp: Option<serde_json::Value>,
}
#[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,
+2
View File
@@ -66,3 +66,5 @@ pub mod sampling;
pub mod server_api;
pub mod settings;
pub mod mcp;
+13
View File
@@ -841,6 +841,15 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
trusted_origins: Arc::new(config.trusted_origins.clone()),
..Default::default()
};
if !config.mcp_servers.is_empty() {
let hub = Arc::new(strata_control::mcp::Hub::new(
std::mem::take(&mut config.mcp_servers),
config.mcp_settings.clone(),
));
state.mcp = Some(hub.clone());
// Servers start in the background (npx may download a package first); GET /mcp shows progress.
tokio::spawn(async move { hub.start().await });
}
if config.cors_origins.iter().any(|o| o == "*") && config.api_key.is_none() {
eprintln!("CORS on /v1/*: WARNING: any web page may use the model (no API key)");
}
@@ -880,6 +889,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
}
eprintln!("strata-control listening on {}", listener.local_addr()?);
let server_shutdown = shutdown_tx.clone();
let state_mcp = state.mcp.clone();
let lifecycle = state.lifecycle.clone();
let shutdown_grace = config.shutdown_grace;
let result = axum::serve(listener, app::router(state))
@@ -893,6 +903,9 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
})
.await;
let _ = shutdown_tx.send(true);
if let Some(hub) = &state_mcp {
hub.close().await;
}
if let Some(task) = worker_task {
task.await?;
}
File diff suppressed because it is too large Load Diff
+11 -3
View File
@@ -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());
}
+9
View File
@@ -531,3 +531,12 @@ pub async fn cors_layer(State(cors): State<Arc<Cors>>, 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<AppState>) -> Response {
let body = match &state.mcp {
Some(hub) => hub.status().await,
None => json!({"servers": [], "tools": 0}),
};
reply(StatusCode::OK, body)
}
+444
View File
@@ -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<String, Value> {
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<String, Value>)>, settings: Settings) -> Hub {
Hub::new(
servers
.into_iter()
.map(|(n, c)| (n.to_owned(), c))
.collect::<BTreeMap<_, _>>(),
settings,
)
}
fn names(status: &Value, server: &str) -> Vec<String> {
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<String> = 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::<Vec<_>>()
);
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::<Vec<_>>(), ["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;
}
+10
View File
@@ -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 `<server>__<tool>`, 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