Files
leleka/control-plane/src/server_api.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 76d57a549c 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>
2026-10-14 15:51:13 +02:00

543 lines
19 KiB
Rust

//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`)
//! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`,
//! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and
//! the own-page guard. Behaviour is checked against the real Python handlers in
//! `tests/http_surface.rs` (fixtures from `tests/golden/gen_goldens.py http`).
//!
//! One engine at a time: `total_slots` is 1 and `/slots` lists one slot while the engine is loaded.
use std::{
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use axum::{
Json,
body::Bytes,
extract::{Request, State},
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header},
middleware::Next,
response::{IntoResponse, Response},
};
use leleka_serving_policy::{
cors::{Cors, own_page},
idle::Outcome,
};
use serde_json::{Value, json};
use tokio::sync::{mpsc, oneshot};
use crate::{
app::AppState,
worker::{Control, LoadError, WorkerState, WorkerStatus},
};
/// The chat template the Original serves in `/props` when the model ships none.
pub const DEFAULT_CHAT_TEMPLATE: &str =
include_str!("../../engine/strata/serve/chat_template.jinja");
fn error_body(kind: Option<&str>, message: &str) -> Value {
match kind {
Some(kind) => json!({"error": {"type": kind, "message": message}}),
None => json!({"error": {"message": message}}),
}
}
fn reply(status: StatusCode, body: Value) -> Response {
(status, Json(body)).into_response()
}
fn now_s() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name).and_then(|v| v.to_str().ok())
}
fn is_loaded(worker: &WorkerStatus) -> bool {
worker.state == WorkerState::Ready
}
/// Whether a request is running or waiting for the engine.
fn is_busy(state: &AppState, worker: &WorkerStatus) -> bool {
worker.metrics.active_since.is_some() || state.lifecycle.snapshot().generation_jobs > 0
}
fn context_of(worker: &WorkerStatus) -> usize {
worker.max_context.or(worker.known_max_context).unwrap_or(0)
}
// ------------------------------------------------------------------------------------------------ loading
/// Start the engine if it is unloaded (the Original's `Service.load`, called at the start of every
/// request). Stamps the activity time so the idle timer does not unload between this and the
/// request's own start. `Err` is a ready-made error response.
pub async fn ensure_loaded(state: &AppState) -> Result<(), Box<Response>> {
let unloaded = {
let mut worker = state.worker.write().await;
worker.last_activity = Some(tokio::time::Instant::now());
worker.state == WorkerState::Unloaded
};
if !unloaded {
return Ok(());
}
match load(state).await {
Ok(()) => Ok(()),
Err(error) => Err(Box::new(load_error_response(&error))),
}
}
/// Ask the supervisor to load and wait until it is ready.
pub async fn load(state: &AppState) -> Result<(), LoadError> {
let Some(control) = &state.control else {
return Err(LoadError::Failed(
"the engine cannot be loaded on demand".into(),
));
};
let (answer, received) = oneshot::channel();
control
.send(Control::Load { reply: answer })
.await
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?;
received
.await
.map_err(|_| LoadError::Failed("the server is shutting down".into()))?
}
/// `POST /unload`'s core (also the idle thread): the outcome string of the Original.
pub async fn unload(state: &AppState, idle_for: Option<Duration>) -> Outcome {
let Some(control) = &state.control else {
return Outcome::Unsupported;
};
{
let worker = state.worker.read().await;
if is_loaded(&worker) && is_busy(state, &worker) {
return Outcome::Busy;
}
}
let (answer, received) = oneshot::channel();
if control
.send(Control::Unload {
idle_for,
reply: answer,
})
.await
.is_err()
{
return Outcome::NotLoaded;
}
received.await.unwrap_or(Outcome::NotLoaded)
}
fn load_error_response(error: &LoadError) -> Response {
let message = match error {
LoadError::GpuBusy(m) | LoadError::Failed(m) => m,
};
api_server_error(message)
}
fn api_server_error(message: &str) -> Response {
reply(
StatusCode::SERVICE_UNAVAILABLE,
error_body(Some("server_error"), message),
)
}
/// The idle thread of `--idle-unload`: every `poll` seconds, give the engine back if no request ran
/// within `idle`. Returns when the control channel closes.
pub async fn idle_unload_loop(state: AppState, idle: Duration, poll: Duration) {
loop {
tokio::time::sleep(poll).await;
if state.control.as_ref().is_none_or(mpsc::Sender::is_closed) {
return;
}
let outcome = unload(&state, Some(idle)).await;
if outcome == Outcome::Unloaded {
eprintln!(
"model unloaded after {:.0} s idle; the next request loads it again",
idle.as_secs_f64()
);
}
}
}
// ------------------------------------------------------------------------------------------------ handlers
/// `GET /api/health` (the Python server's `/health`): who answers and whether the engine is loaded.
pub async fn api_health(State(state): State<AppState>) -> Response {
let worker = *state.worker.read().await;
reply(
StatusCode::OK,
json!({"status": "ok", "max_context": context_of(&worker), "model": state.model,
"images": false, "api_key": state.api_key.is_some(),
"loaded": is_loaded(&worker), "service": "strata"}),
)
}
fn model_names(state: &AppState) -> Vec<String> {
state
.model
.iter()
.cloned()
.chain(state.aliases.iter().cloned())
.collect()
}
/// The first non-blank value of `name` (Python's `parse_qs` drops blank values).
fn query_param(query: Option<&str>, name: &str) -> Option<String> {
query?.split('&').find_map(|pair| {
let (key, value) = pair.split_once('=')?;
(percent_decode(key) == name && !value.is_empty()).then(|| percent_decode(value))
})
}
fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => out.push(b' '),
b'%' if i + 2 < bytes.len() => {
match std::str::from_utf8(&bytes[i + 1..i + 3])
.ok()
.and_then(|hex| u8::from_str_radix(hex, 16).ok())
{
Some(byte) => {
out.push(byte);
i += 2;
}
None => out.push(b'%'),
}
}
byte => out.push(byte),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// `GET /props` (llama-server compatible): the default generation settings, the chat template and
/// what this server can do.
pub async fn props(State(state): State<AppState>, request: Request) -> Response {
let asked = query_param(request.uri().query(), "model")
.or_else(|| state.model.clone())
.unwrap_or_default();
if !model_names(&state).contains(&asked) {
return reply(StatusCode::NOT_FOUND, error_body(None, "model not found"));
}
let worker = *state.worker.read().await;
if !is_loaded(&worker) && worker.state != WorkerState::Unloaded {
return reply(
StatusCode::SERVICE_UNAVAILABLE,
error_body(None, "the engine is not running"),
);
}
let merged = state.settings.merged();
let shared = state.settings.shared();
reply(
StatusCode::OK,
json!({
"default_generation_settings": {
"n_ctx": context_of(&worker),
"params": merged.props_params(&shared),
},
"total_slots": 1,
"model_alias": state.model,
"chat_template": state.chat_template.as_deref().unwrap_or(DEFAULT_CHAT_TEMPLATE),
"modalities": {"vision": false},
"models_autoload": state.control.is_some(),
"is_sleeping": !is_loaded(&worker),
"build_info": format!("Strata Next {}", env!("CARGO_PKG_VERSION")),
}),
)
}
/// `GET /slots`: one slot while the engine is loaded, none otherwise.
pub async fn slots(State(state): State<AppState>) -> Response {
let worker = *state.worker.read().await;
if !is_loaded(&worker) {
return reply(StatusCode::OK, json!([]));
}
reply(
StatusCode::OK,
json!([{"id": 0, "n_ctx": context_of(&worker),
"is_processing": is_busy(&state, &worker)}]),
)
}
/// `GET /v1/status`: what this server is and does, for a client that would rather ask than guess.
pub async fn v1_status(State(state): State<AppState>) -> Response {
reply(StatusCode::OK, status_value(&state).await)
}
async fn status_value(state: &AppState) -> Value {
let worker = *state.worker.read().await;
let lifecycle = state.lifecycle.snapshot();
let busy = worker.metrics.active_since.is_some();
let queued = lifecycle.generation_jobs.saturating_sub(usize::from(busy));
let context = context_of(&worker);
let last_at = worker
.last_activity
.map(|at| now_s().saturating_sub(at.elapsed().as_secs()));
let started = state
.started_at
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let timings = worker.metrics.last_done.map(|done| {
let mut value = leleka_serving_policy::timings::request_timings(
&leleka_serving_policy::timings::Last {
prompt_tokens: done.prompt_tokens,
generated: done.generated_tokens,
prompt_ms: done.prefill_ms,
decode_ms: done.decode_ms,
reused: done.reused_tokens,
drafts_offered: done.drafts_offered,
drafts_accepted: done.drafts_accepted,
},
done.generated_tokens,
);
value["at"] = json!(now_s());
value
});
json!({
"service": "strata", "model": state.model,
"loaded": is_loaded(&worker), "auto_load": state.control.is_some(),
"structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate",
"constrained_decoding": false, "stream_buffered": true},
"engine": env!("CARGO_PKG_VERSION"),
"started": started,
"uptime_s": state.started_at.elapsed().map_or(0, |d| d.as_secs()),
"cache_max_tokens": context,
"context": {"native": context, "max_positions": context},
"concurrency": {"serving": 1, "requested": 1},
"dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],
"vision": {"enabled": false, "available": false, "error": null},
"activity": {"requests": worker.metrics.started, "in_flight": usize::from(busy) + queued,
"last_request_at": last_at},
"last_timings": timings,
"machine": {"at": now_s(), "gpu": null, "ram": null},
})
}
/// `GET /settings`.
pub async fn settings_get(State(state): State<AppState>) -> Response {
let shared = state.settings.shared();
reply(
StatusCode::OK,
json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}),
)
}
fn own_page_check(state: &AppState, headers: &HeaderMap, what: &str) -> Result<(), Box<Response>> {
own_page(
what,
header_str(headers, "content-type"),
header_str(headers, "origin"),
header_str(headers, "host"),
&state.trusted_origins,
)
.map_err(|e| {
Box::new(reply(
StatusCode::from_u16(e.status()).unwrap_or(StatusCode::FORBIDDEN),
error_body(None, &e.message()),
))
})
}
/// `POST /settings`: replace the Chat settings every client gets for what it leaves out. They change
/// what every client gets, so only the app's own page may set them.
pub async fn settings_post(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
if let Err(response) = own_page_check(&state, &headers, "settings can be changed") {
return *response;
}
let value: Value = if body.is_empty() {
json!({})
} else {
match serde_json::from_slice(&body) {
Ok(value) => value,
Err(error) => {
return reply(
StatusCode::BAD_REQUEST,
error_body(Some("invalid_request_error"), &error.to_string()),
);
}
}
};
let defaults = value.get("defaults").cloned().unwrap_or(Value::Null);
match state.settings.set_shared(&defaults) {
Ok(shared) => {
if shared.is_empty() {
eprintln!("other apps use their own settings again");
} else {
eprintln!("other apps now use the Chat settings: {}", shared.to_json());
}
reply(
StatusCode::OK,
json!({"shared": !shared.is_empty(), "defaults": shared.to_json()}),
)
}
Err(message) => reply(
StatusCode::BAD_REQUEST,
error_body(Some("invalid_request_error"), &message),
),
}
}
/// `POST /unload`: give the GPU back now (between requests).
pub async fn unload_post(State(state): State<AppState>) -> Response {
let outcome = unload(&state, None).await;
reply(
if outcome == Outcome::Busy {
StatusCode::CONFLICT
} else {
StatusCode::OK
},
json!({"status": outcome.as_str()}),
)
}
/// `POST /load`: load now, e.g. ahead of a request.
pub async fn load_post(State(state): State<AppState>) -> Response {
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
if state.worker.read().await.state == WorkerState::Ready {
return reply(StatusCode::OK, json!({"status": "loaded"}));
}
match load(&state).await {
Ok(()) => reply(StatusCode::OK, json!({"status": "loaded"})),
Err(error) => load_error_response(&error),
}
}
/// The shared prelude of `POST /v1/load` and `/v1/unload`: a JSON object body, own page only, and
/// the right model.
fn model_control_prelude(
state: &AppState,
headers: &HeaderMap,
body: &Bytes,
) -> Result<(), Box<Response>> {
let value: Value = if body.is_empty() {
json!({})
} else {
serde_json::from_slice(body).map_err(|error| {
Box::new(reply(
StatusCode::BAD_REQUEST,
error_body(Some("invalid_request_error"), &error.to_string()),
))
})?
};
let Some(object) = value.as_object() else {
return Err(Box::new(reply(
StatusCode::BAD_REQUEST,
error_body(Some("invalid_request_error"), "send a JSON object"),
)));
};
own_page_check(state, headers, "the model can be loaded or unloaded")?;
match object.get("model") {
None | Some(Value::Null) => {}
Some(Value::String(name)) if state.model.as_deref() == Some(name.as_str()) => {}
Some(_) => {
return Err(Box::new(reply(
StatusCode::NOT_FOUND,
error_body(None, "model not found"),
)));
}
}
Ok(())
}
fn model_busy() -> Response {
reply(
StatusCode::CONFLICT,
error_body(Some("model_busy"), "a request is running or queued"),
)
}
pub async fn v1_unload(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
if let Err(response) = model_control_prelude(&state, &headers, &body) {
return *response;
}
let outcome = unload(&state, None).await;
if outcome == Outcome::Busy {
return model_busy();
}
let mut value = status_value(&state).await;
value["status"] = json!(outcome.as_str());
reply(StatusCode::OK, value)
}
pub async fn v1_load(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
if let Err(response) = model_control_prelude(&state, &headers, &body) {
return *response;
}
{
let worker = state.worker.read().await;
if is_busy(&state, &worker) {
return model_busy();
}
}
state.worker.write().await.last_activity = Some(tokio::time::Instant::now());
if state.worker.read().await.state != WorkerState::Ready
&& let Err(error) = load(&state).await
{
return load_error_response(&error);
}
let mut value = status_value(&state).await;
value["status"] = json!("loaded");
reply(StatusCode::OK, value)
}
/// Unknown paths: a JSON error, like the Original's `{"error": {"message": "not found"}}`.
pub async fn not_found() -> Response {
reply(StatusCode::NOT_FOUND, error_body(None, "not found"))
}
// ------------------------------------------------------------------------------------------------ CORS
/// CORS for `/v1/*` (config `cors_origins`) and the preflight: the outermost layer, so a browser's
/// credential-less `OPTIONS` is answered before authentication, as the Original does.
pub async fn cors_layer(State(cors): State<Arc<Cors>>, request: Request, next: Next) -> Response {
let target = request.uri().path_and_query().map_or_else(
|| request.uri().path().to_owned(),
|p| p.as_str().to_owned(),
);
let headers = cors.headers(
&target,
header_str(request.headers(), "origin"),
header_str(request.headers(), "access-control-request-headers"),
);
let mut response = if request.method() == Method::OPTIONS {
let mut response = StatusCode::NO_CONTENT.into_response();
response
.headers_mut()
.insert(header::CONTENT_LENGTH, HeaderValue::from_static("0"));
response
} else {
next.run(request).await
};
for (name, value) in headers {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(&value),
) {
response.headers_mut().insert(name, value);
}
}
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)
}