Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

12.0 KB
Raw Blame
//! MCP server registry and per-kwant assignment endpoints. Contract: docs/mcp-api.md.

use super::spaces::Scope;
use super::{mcp_oauth::{self, TokenUse}, AppState};
use crate::db::spaces::SpaceId;
use crate::db::{models::McpServer, DbError};
use crate::mcp::{self, McpClient, McpError, McpServerInput, McpServerView};
use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};
use serde::Deserialize;
use serde_json::{json, Value};
use std::time::Instant;

type ApiError = (StatusCode, Json<Value>);
type ApiResult<T> = Result<Json<T>, ApiError>;

fn err(status: StatusCode, message: impl Into<String>) -> ApiError {
    (status, Json(json!({ "error": message.into() })))
}

const NAME_TAKEN: &str = "an MCP server with that name already exists";

pub(super) fn db_err(e: DbError) -> ApiError {
    if let DbError::Sqlx(sqlx::Error::Database(ref d)) = e {
        if d.is_unique_violation() {
            return err(StatusCode::CONFLICT, NAME_TAKEN);
        }
    }
    tracing::warn!(error = %e, "MCP registry database error");
    err(StatusCode::INTERNAL_SERVER_ERROR, "database error")
}

/// Which kwants have each server off. A read failure shows no opt-outs rather than failing the list.
async fn opt_outs(state: &AppState, space: &SpaceId) -> std::collections::HashMap<String, Vec<String>> {
    state.db.list_mcp_kwant_opt_outs(space).await.unwrap_or_else(|e| {
        tracing::warn!(error = %e, "could not read MCP kwant opt-outs");
        Default::default()
    })
}

/// The API view of `server`, with its sign-in status.
pub(super) async fn view(state: &AppState, server: &McpServer) -> McpServerView {
    let mut view = McpServerView::from(server);
    view.oauth = mcp_oauth::statuses(state).await.remove(&server.id).unwrap_or_default();
    let space = state.db.space_of_mcp_server(&server.id).await.ok().flatten().unwrap_or_else(SpaceId::default_space);
    view.disabled_for_kwants = opt_outs(state, &space).await.remove(&server.id).unwrap_or_default();
    view
}

pub async fn list_servers(State(state): State<AppState>, Scope(space): Scope) -> ApiResult<Vec<McpServerView>> {
    let servers = state.db.list_mcp_servers(&space).await.map_err(db_err)?;
    let mut statuses = mcp_oauth::statuses(&state).await;
    let mut opt_outs = opt_outs(&state, &space).await;
    Ok(Json(
        servers
            .iter()
            .map(|s| McpServerView {
                oauth: statuses.remove(&s.id).unwrap_or_default(),
                disabled_for_kwants: opt_outs.remove(&s.id).unwrap_or_default(),
                ..McpServerView::from(s)
            })
            .collect(),
    ))
}

pub async fn get_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<McpServerView> {
    match state.db.get_mcp_server(&id).await.map_err(db_err)? {
        Some(s) => Ok(Json(view(&state, &s).await)),
        None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),
    }
}

/// Two server names a bot could not tell apart: equal ignoring case and surrounding spaces (the
/// rule `mcp_suggest::free_name` uses for directory installs).
fn same_server_name(a: &str, b: &str) -> bool {
    a.trim().eq_ignore_ascii_case(b.trim())
}

/// The same 409 as the unique index when another server in `space` (not `except`, the one being
/// edited) already has `name` in another case. The index only catches an exact match.
async fn check_name_free(state: &AppState, space: &SpaceId, name: &str, except: Option<&str>) -> Result<(), ApiError> {
    let servers = state.db.list_mcp_servers(space).await.map_err(db_err)?;
    if servers.iter().any(|s| Some(s.id.as_str()) != except && same_server_name(&s.name, name)) {
        return Err(err(StatusCode::CONFLICT, NAME_TAKEN));
    }
    Ok(())
}

pub async fn create_server(
    State(state): State<AppState>,
    Scope(space): Scope,
    Json(input): Json<McpServerInput>,
) -> ApiResult<McpServerView> {
    let server = mcp::build_server(input, None).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;
    check_name_free(&state, &space, &server.name, None).await?;
    let created = state.db.create_mcp_server(&space, &server).await.map_err(db_err)?;
    Ok(Json(McpServerView::from(&created)))
}

pub async fn update_server(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Json(input): Json<McpServerInput>,
) -> ApiResult<McpServerView> {
    let existing = state
        .db
        .get_mcp_server(&id)
        .await
        .map_err(db_err)?
        .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;
    let server = mcp::build_server(input, Some(&existing)).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;
    // Only a new name is checked, so a case-only pair saved before this rule can still be edited and switched
    if server.name != existing.name {
        let space = state.db.space_of_mcp_server(&id).await.map_err(db_err)?.unwrap_or_else(SpaceId::default_space);
        check_name_free(&state, &space, &server.name, Some(&id)).await?;
    }
    let updated = state.db.update_mcp_server(&server).await.map_err(db_err)?;
    if updated.is_some() && (server.url != existing.url || server.transport != existing.transport) {
        // Tokens and registrations belong to the old address
        state.db.clear_mcp_oauth(&id).await.map_err(db_err)?;
    }
    if updated.is_some()
        && (server.url != existing.url || server.transport != existing.transport || server.command != existing.command || server.args != existing.args)
    {
        // Another address or program may be another server: what it said it was is asked again (26f)
        state.db.forget_mcp_server_facts(&id).await.map_err(db_err)?;
        mcp::home_floor::forget(&id);
    }
    match updated {
        Some(s) => Ok(Json(view(&state, &s).await)),
        None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),
    }
}

pub async fn delete_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {
    if state.db.delete_mcp_server(&id).await.map_err(db_err)? {
        mcp::home_floor::forget(&id);
        Ok(Json(json!({ "status": "deleted" })))
    } else {
        Err(err(StatusCode::NOT_FOUND, "MCP server not found"))
    }
}

/// Connects once and lists the tools.
async fn try_list(server: &McpServer, cwd: &std::path::Path) -> Result<(Value, Vec<mcp::McpTool>), (McpError, String)> {
    match McpClient::connect(server, Some(cwd)).await {
        Ok(mut client) => {
            let tools = client.list_tools().await;
            let stderr_tail = client.stderr_tail();
            client.shutdown().await;
            tools.map(|t| (client.server_info.clone(), t)).map_err(|e| (e, stderr_tail))
        }
        Err(e) => {
            let stderr_tail = match e {
                McpError::Startup { ref stderr_tail, .. } => stderr_tail.clone(),
                _ => String::new(),
            };
            Err((e, stderr_tail))
        }
    }
}

/// Connects with the stored config (and sign-in), lists the tools and disconnects. Errors are
/// redacted. A 401 without a usable sign-in answers `auth_required: true`.
pub async fn test_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {
    let stored = state
        .db
        .get_mcp_server(&id)
        .await
        .map_err(db_err)?
        .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;
    Ok(Json(run_test(&state, &stored).await))
}

/// What `test_server` answers for `stored`.
pub(super) async fn run_test(state: &AppState, stored: &McpServer) -> Value {
    let id = &stored.id;
    let start = Instant::now();
    let cwd = state.config.data_dir.join("workspace");

    let mut server = stored.clone();
    let token_use = mcp_oauth::authorize_server(state, &mut server).await;
    let mut secrets = server.secret_values();
    // The same D4 rule as a turn's (C8): from a folder an isolated bot used, a stdio server
    // starts from an empty one, or not at all when it runs a file from there
    let token = uuid::Uuid::new_v4().simple().to_string();
    let mut one = vec![server];
    let empty = super::mcp_runtime::isolate_stdio_servers(state, &mut one, Some(&cwd), &token).await;
    let Some(server) = one.pop() else {
        let outcome = json!({ "ok": false, "error": "Not started: it runs a file from a folder an isolated bot used, \
                                                   or no empty folder could be made for it",
                              "duration_ms": start.elapsed().as_millis() as u64 });
        super::connections::record_mcp_check(&stored.id, &outcome);
        return outcome;
    };
    let mut result = try_list(&server, &cwd).await;
    if token_use == TokenUse::Injected && matches!(result, Err((McpError::Unauthorized { .. }, _))) {
        // The token was rejected early (revoked, or the server's clock): refresh once
        if let Some(mut retry) = mcp_oauth::retry_after_unauthorized(state, stored).await {
            if let Some(dir) = &empty {
                mcp::start_in(&mut retry, dir);
            }
            secrets.extend(retry.secret_values());
            result = try_list(&retry, &cwd).await;
        }
    }
    if empty.is_some() {
        super::mcp_runtime::remove_mcp_cwd(state, &token).await;
    }

    if let Ok((server_info, _)) = &result {
        // 26f: stored with the server, so its locks ask also before kwnt next connects to it
        let reported = mcp::home_floor::reported_name(server_info);
        if let Err(e) = state.db.save_mcp_reported_name(id, reported.as_deref()).await {
            tracing::warn!(error = %e, server = %stored.name, "could not store what the MCP server said it is");
        }
    }
    let mut outcome = match result {
        Ok((server_info, tools)) => json!({ "ok": true, "server_info": server_info, "tools": tools }),
        Err((McpError::Unauthorized { .. }, _)) if token_use != TokenUse::UserHeader => {
            if token_use == TokenUse::Injected {
                // Still rejected after a refresh: the sign-in is no longer valid
                let _ = state.db.delete_mcp_oauth_token(id).await;
            }
            json!({ "ok": false, "auth_required": true, "error": "Sign-in required" })
        }
        Err((e, stderr_tail)) => json!({ "ok": false, "error": mcp::redact(&e.to_string(), &secrets),
                                         "stderr_tail": mcp::redact(&stderr_tail, &secrets) }),
    };
    outcome["duration_ms"] = json!(start.elapsed().as_millis() as u64);
    super::connections::record_mcp_check(&stored.id, &outcome);
    outcome
}

pub async fn get_kwant_servers(State(state): State<AppState>, Path(kwant_id): Path<String>) -> ApiResult<Value> {
    if state.db.get_kwant(&kwant_id).await.map_err(db_err)?.is_none() {
        return Err(err(StatusCode::NOT_FOUND, "bot not found"));
    }
    let ids = state.db.get_kwant_mcp_server_ids(&kwant_id).await.map_err(db_err)?;
    Ok(Json(json!({ "server_ids": ids })))
}

#[derive(Debug, Deserialize)]
pub struct AssignServers {
    pub server_ids: Vec<String>,
}

pub async fn set_kwant_servers(
    State(state): State<AppState>,
    Path(kwant_id): Path<String>,
    Json(body): Json<AssignServers>,
) -> ApiResult<Value> {
    let Some(space) = state.db.space_of_kwant(&kwant_id).await.map_err(db_err)? else {
        return Err(err(StatusCode::NOT_FOUND, "bot not found"));
    };
    // Only servers in the kwant's own space can be assigned to it
    let known: Vec<String> = state.db.list_mcp_servers(&space).await.map_err(db_err)?.into_iter().map(|s| s.id).collect();
    if let Some(unknown) = body.server_ids.iter().find(|id| !known.contains(id)) {
        return Err(err(StatusCode::BAD_REQUEST, format!("unknown MCP server id '{unknown}'")));
    }
    state.db.set_kwant_mcp_servers(&kwant_id, &body.server_ids).await.map_err(db_err)?;
    let ids = state.db.get_kwant_mcp_server_ids(&kwant_id).await.map_err(db_err)?;
    Ok(Json(json!({ "server_ids": ids })))
}

#[cfg(test)]
mod tests {
    use super::same_server_name;

    #[test]
    fn names_match_ignoring_case_and_surrounding_spaces() {
        assert!(same_server_name("stripe", "Stripe"));
        assert!(same_server_name(" STRIPE ", "stripe"));
        assert!(!same_server_name("stripe", "stripe-2"));
    }
}