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.

MCP server registry, client and per-kwant assignment

Lin (kwant bot)da62e70e6dea
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 1c6a1a81..7205aca0 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -500,5 +500,125 @@ impl Database {
.await?;
Ok(res.rows_affected() > 0)
}
+
+ // MCP servers
+ pub async fn list_mcp_servers(&self) -> Result<Vec<McpServer>, DbError> {
+ let rows = sqlx::query_as::<_, McpServerRow>("SELECT * FROM mcp_servers ORDER BY name ASC")
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(McpServer::from_row).collect())
+ }
+
+ pub async fn get_mcp_server(&self, id: &str) -> Result<Option<McpServer>, DbError> {
+ let row = sqlx::query_as::<_, McpServerRow>("SELECT * FROM mcp_servers WHERE id = ?")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.map(McpServer::from_row))
+ }
+
+ /// Inserts `server` with a fresh id (any id passed in is ignored).
+ pub async fn create_mcp_server(&self, server: &McpServer) -> Result<McpServer, DbError> {
+ let id = Uuid::new_v4().to_string();
+ sqlx::query(
+ "INSERT INTO mcp_servers (id, name, transport, command, args, url, env, headers, enabled, timeout_secs) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(&server.name)
+ .bind(&server.transport)
+ .bind(&server.command)
+ .bind(serde_json::to_string(&server.args)?)
+ .bind(&server.url)
+ .bind(serde_json::to_string(&server.env)?)
+ .bind(serde_json::to_string(&server.headers)?)
+ .bind(server.enabled)
+ .bind(server.timeout_secs)
+ .execute(&self.pool)
+ .await?;
+ self.get_mcp_server(&id)
+ .await?
+ .ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))
+ }
+
+ pub async fn update_mcp_server(&self, server: &McpServer) -> Result<Option<McpServer>, DbError> {
+ let res = sqlx::query(
+ "UPDATE mcp_servers SET name = ?, transport = ?, command = ?, args = ?, url = ?, env = ?, headers = ?, \
+ enabled = ?, timeout_secs = ? WHERE id = ?",
+ )
+ .bind(&server.name)
+ .bind(&server.transport)
+ .bind(&server.command)
+ .bind(serde_json::to_string(&server.args)?)
+ .bind(&server.url)
+ .bind(serde_json::to_string(&server.env)?)
+ .bind(serde_json::to_string(&server.headers)?)
+ .bind(server.enabled)
+ .bind(server.timeout_secs)
+ .bind(&server.id)
+ .execute(&self.pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Ok(None);
+ }
+ self.get_mcp_server(&server.id).await
+ }
+
+ /// Deletes the server and its kwant assignments. `foreign_keys` is only set on one pooled
+ /// connection, so the cascade is done here rather than trusted to SQLite.
+ pub async fn delete_mcp_server(&self, id: &str) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("DELETE FROM kwant_mcp_servers WHERE server_id = ?")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ let res = sqlx::query("DELETE FROM mcp_servers WHERE id = ?")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ pub async fn get_kwant_mcp_server_ids(&self, kwant_id: &str) -> Result<Vec<String>, DbError> {
+ let rows: Vec<(String,)> = sqlx::query_as(
+ "SELECT a.server_id FROM kwant_mcp_servers a JOIN mcp_servers s ON s.id = a.server_id \
+ WHERE a.kwant_id = ? ORDER BY s.name ASC",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(|r| r.0).collect())
+ }
+
+ /// Replaces the kwant's whole assignment. Callers validate that every id exists.
+ pub async fn set_kwant_mcp_servers(&self, kwant_id: &str, server_ids: &[String]) -> Result<(), DbError> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("DELETE FROM kwant_mcp_servers WHERE kwant_id = ?")
+ .bind(kwant_id)
+ .execute(&mut *tx)
+ .await?;
+ for server_id in server_ids {
+ sqlx::query("INSERT OR IGNORE INTO kwant_mcp_servers (kwant_id, server_id) VALUES (?, ?)")
+ .bind(kwant_id)
+ .bind(server_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// The enabled servers assigned to a kwant: what it may use on its next turn.
+ pub async fn list_active_mcp_servers_for_kwant(&self, kwant_id: &str) -> Result<Vec<McpServer>, DbError> {
+ let rows = sqlx::query_as::<_, McpServerRow>(
+ "SELECT s.* FROM mcp_servers s JOIN kwant_mcp_servers a ON a.server_id = s.id \
+ WHERE a.kwant_id = ? AND s.enabled = 1 ORDER BY s.name ASC",
+ )
+ .bind(kwant_id)
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(McpServer::from_row).collect())
+ }
}
diff --git a/src/db/models.rs b/src/db/models.rs
index 75f8024e..77e08e16 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -137,3 +137,77 @@ pub struct NewTeam {
pub repo_url: Option<String>,
}
+
+/// Raw `mcp_servers` row; JSON columns are decoded by [`McpServer::from_row`].
+#[derive(Clone, FromRow)]
+pub struct McpServerRow {
+ pub id: String,
+ pub name: String,
+ pub transport: String,
+ pub command: Option<String>,
+ pub args: String,
+ pub url: Option<String>,
+ pub env: String,
+ pub headers: String,
+ pub enabled: bool,
+ pub timeout_secs: i64,
+ pub created_at: Option<DateTime<Utc>>,
+}
+
+/// A registered MCP server, secrets included. Deliberately not `Serialize`: the API returns
+/// `crate::mcp::McpServerView`, which masks `env` and `headers`.
+#[derive(Clone, PartialEq)]
+pub struct McpServer {
+ pub id: String,
+ pub name: String,
+ pub transport: String, // "stdio" | "http"
+ pub command: Option<String>,
+ pub args: Vec<String>,
+ pub url: Option<String>,
+ pub env: std::collections::BTreeMap<String, String>,
+ pub headers: std::collections::BTreeMap<String, String>,
+ pub enabled: bool,
+ pub timeout_secs: i64,
+ pub created_at: Option<DateTime<Utc>>,
+}
+
+impl McpServer {
+ pub fn from_row(row: McpServerRow) -> Self {
+ Self {
+ id: row.id,
+ name: row.name,
+ transport: row.transport,
+ command: row.command,
+ args: serde_json::from_str(&row.args).unwrap_or_default(),
+ url: row.url,
+ env: serde_json::from_str(&row.env).unwrap_or_default(),
+ headers: serde_json::from_str(&row.headers).unwrap_or_default(),
+ enabled: row.enabled,
+ timeout_secs: row.timeout_secs,
+ created_at: row.created_at,
+ }
+ }
+
+ /// Every stored secret value, for redacting text that may echo them.
+ pub fn secret_values(&self) -> Vec<String> {
+ self.env.values().chain(self.headers.values()).cloned().collect()
+ }
+}
+
+/// Never prints secret values.
+impl std::fmt::Debug for McpServer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("McpServer")
+ .field("id", &self.id)
+ .field("name", &self.name)
+ .field("transport", &self.transport)
+ .field("command", &self.command)
+ .field("args", &self.args)
+ .field("url", &self.url)
+ .field("env_keys", &self.env.keys().collect::<Vec<_>>())
+ .field("header_keys", &self.headers.keys().collect::<Vec<_>>())
+ .field("enabled", &self.enabled)
+ .field("timeout_secs", &self.timeout_secs)
+ .finish()
+ }
+}
diff --git a/src/db/schema.sql b/src/db/schema.sql
index cd16dce0..6dc6b716 100644
--- a/src/db/schema.sql
+++ b/src/db/schema.sql
@@ -66,3 +66,25 @@ CREATE TABLE IF NOT EXISTS teams (
FOREIGN KEY(lead_kwant_id) REFERENCES kwants(id)
);
+
+CREATE TABLE IF NOT EXISTS mcp_servers (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ transport TEXT NOT NULL,
+ command TEXT,
+ args TEXT NOT NULL DEFAULT '[]',
+ url TEXT,
+ env TEXT NOT NULL DEFAULT '{}',
+ headers TEXT NOT NULL DEFAULT '{}',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ timeout_secs INTEGER NOT NULL DEFAULT 30,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE IF NOT EXISTS kwant_mcp_servers (
+ kwant_id TEXT NOT NULL,
+ server_id TEXT NOT NULL,
+ PRIMARY KEY (kwant_id, server_id),
+ FOREIGN KEY(kwant_id) REFERENCES kwants(id) ON DELETE CASCADE,
+ FOREIGN KEY(server_id) REFERENCES mcp_servers(id) ON DELETE CASCADE
+);
diff --git a/src/lib.rs b/src/lib.rs
index 69f881e4..606829b3 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,6 +3,7 @@ pub mod config;
pub mod db;
pub mod drivers;
pub mod embedded;
+pub mod mcp;
pub mod router;
pub mod sandbox;
pub mod server;
diff --git a/src/main.rs b/src/main.rs
index 588fc595..10b5360f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -55,13 +55,22 @@ pub enum Commands {
/// List channels stored in the local database
Channels,
+
+ /// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)
+ #[command(hide = true)]
+ McpEchoServer,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let cli = Cli::parse();
+ // Before logging starts: stdout carries the MCP protocol
+ if matches!(cli.command, Some(Commands::McpEchoServer)) {
+ kwnt::mcp::echo_server::run_stdio().await?;
+ return Ok(());
+ }
tracing_subscriber::fmt::init();
- let cli = Cli::parse();
let mut config = match cli.config {
Some(path) => Config::from_file(path)?,
None => Config::load()?,
@@ -144,6 +153,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Some(Commands::Agents) => print_agents(&config).await?,
Some(Commands::Teams) => print_teams(&config).await?,
Some(Commands::Channels) => print_channels(&config).await?,
+ Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),
None => {
println!("⚡ Kwant: your team of super-intelligent bots (kwants)");
println!("Run `kwnt serve` to start the server, or `kwnt --help` for options.");
diff --git a/src/mcp/client.rs b/src/mcp/client.rs
new file mode 100644
index 00000000..d351292f
--- /dev/null
+++ b/src/mcp/client.rs
@@ -0,0 +1,484 @@
+//! A small MCP client: JSON-RPC over a child process's stdio, or over streamable HTTP.
+//! Supports what kwnt needs: initialize, tools/list, tools/call, timeouts and clean shutdown.
+
+use crate::db::models::McpServer;
+use futures::StreamExt;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::path::Path;
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::Duration;
+use thiserror::Error;
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::process::{Child, ChildStdin, Command};
+use tokio::sync::{oneshot, Mutex};
+use tokio::task::JoinHandle;
+
+pub const PROTOCOL_VERSION: &str = "2025-06-18";
+/// Variables a stdio server inherits from kwnt; everything else (API keys…) stays private.
+const INHERITED_ENV: [&str; 5] = ["PATH", "HOME", "USER", "LANG", "TMPDIR"];
+const STDERR_TAIL_BYTES: usize = 4096;
+const MAX_TOOL_PAGES: usize = 20;
+
+#[derive(Error, Debug)]
+pub enum McpError {
+ #[error("could not start server: {0}")]
+ Spawn(String),
+ #[error("timed out after {0}s waiting for {1}")]
+ Timeout(u64, String),
+ #[error("server closed the connection")]
+ Closed,
+ #[error("server error {code}: {message}")]
+ Rpc { code: i64, message: String },
+ #[error("transport error: {0}")]
+ Transport(String),
+ #[error("invalid response: {0}")]
+ Protocol(String),
+ /// The server failed before the handshake completed; keeps what it wrote to stderr.
+ #[error("{message}")]
+ Startup { message: String, stderr_tail: String },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct McpTool {
+ pub name: String,
+ pub description: Option<String>,
+ pub input_schema: Value,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct ToolCallResult {
+ pub text: String,
+ pub is_error: bool,
+}
+
+type Pending = Arc<StdMutex<HashMap<i64, oneshot::Sender<Value>>>>;
+
+struct StdioTransport {
+ child: Mutex<Option<Child>>,
+ stdin: Arc<Mutex<Option<ChildStdin>>>,
+ pending: Pending,
+ closed: Arc<AtomicBool>,
+ stderr_tail: Arc<StdMutex<String>>,
+ tasks: Vec<JoinHandle<()>>,
+}
+
+struct HttpTransport {
+ client: reqwest::Client,
+ url: String,
+ headers: reqwest::header::HeaderMap,
+ session_id: StdMutex<Option<String>>,
+ protocol_version: StdMutex<Option<String>>,
+}
+
+enum Transport {
+ Stdio(StdioTransport),
+ Http(HttpTransport),
+}
+
+pub struct McpClient {
+ pub server_name: String,
+ pub server_info: Value,
+ timeout: Duration,
+ next_id: AtomicI64,
+ transport: Transport,
+}
+
+async fn write_line(stdin: &Mutex<Option<ChildStdin>>, msg: &Value) -> Result<(), McpError> {
+ let mut guard = stdin.lock().await;
+ let pipe = guard.as_mut().ok_or(McpError::Closed)?;
+ let mut line = serde_json::to_vec(msg).map_err(|e| McpError::Protocol(e.to_string()))?;
+ line.push(b'\n');
+ pipe.write_all(&line).await.map_err(|_| McpError::Closed)?;
+ pipe.flush().await.map_err(|_| McpError::Closed)
+}
+
+fn response_id(msg: &Value) -> Option<i64> {
+ if msg.get("method").is_some() || (msg.get("result").is_none() && msg.get("error").is_none()) {
+ return None;
+ }
+ msg.get("id")?.as_i64()
+}
+
+/// Text an agent can read from a `tools/call` result.
+fn result_text(result: &Value) -> String {
+ let mut parts = Vec::new();
+ for item in result["content"].as_array().into_iter().flatten() {
+ match item["type"].as_str().unwrap_or("") {
+ "text" => parts.push(item["text"].as_str().unwrap_or("").to_string()),
+ "image" => parts.push(format!("[image: {}]", item["mimeType"].as_str().unwrap_or("?"))),
+ "audio" => parts.push(format!("[audio: {}]", item["mimeType"].as_str().unwrap_or("?"))),
+ "resource" => parts.push(
+ item["resource"]["text"]
+ .as_str()
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("[resource: {}]", item["resource"]["uri"].as_str().unwrap_or("?"))),
+ ),
+ "resource_link" => parts.push(format!("[resource link: {}]", item["uri"].as_str().unwrap_or("?"))),
+ other => parts.push(format!("[{other} content]")),
+ }
+ }
+ if parts.is_empty() {
+ if let Some(structured) = result.get("structuredContent") {
+ return structured.to_string();
+ }
+ }
+ parts.join("\n")
+}
+
+impl McpClient {
+ /// Starts or connects to `server` and completes the MCP handshake. Stdio servers run in `cwd`.
+ pub async fn connect(server: &McpServer, cwd: Option<&Path>) -> Result<Self, McpError> {
+ let timeout = Duration::from_secs(server.timeout_secs.clamp(1, 600) as u64);
+ let transport = match server.transport.as_str() {
+ "stdio" => Transport::Stdio(Self::spawn_stdio(server, cwd)?),
+ "http" => Transport::Http(Self::http_transport(server)?),
+ other => return Err(McpError::Spawn(format!("unknown transport '{other}'"))),
+ };
+ let mut client = Self {
+ server_name: server.name.clone(),
+ server_info: Value::Null,
+ timeout,
+ next_id: AtomicI64::new(1),
+ transport,
+ };
+ match client.handshake().await {
+ Ok(()) => Ok(client),
+ Err(e) => {
+ client.shutdown().await;
+ Err(McpError::Startup { message: e.to_string(), stderr_tail: client.stderr_tail() })
+ }
+ }
+ }
+
+ fn spawn_stdio(server: &McpServer, cwd: Option<&Path>) -> Result<StdioTransport, McpError> {
+ let program = server.command.as_deref().ok_or_else(|| McpError::Spawn("no command".into()))?;
+ let mut cmd = Command::new(program);
+ cmd.args(&server.args).env_clear();
+ for key in INHERITED_ENV {
+ if let Ok(v) = std::env::var(key) {
+ cmd.env(key, v);
+ }
+ }
+ cmd.envs(&server.env);
+ if let Some(dir) = cwd.filter(|d| d.is_dir()) {
+ cmd.current_dir(dir);
+ }
+ cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
+ let mut child = cmd.spawn().map_err(|e| McpError::Spawn(format!("{program}: {e}")))?;
+
+ let stdin = Arc::new(Mutex::new(child.stdin.take()));
+ let stdout = child.stdout.take().ok_or_else(|| McpError::Spawn("no stdout".into()))?;
+ let mut stderr = child.stderr.take().ok_or_else(|| McpError::Spawn("no stderr".into()))?;
+ let pending: Pending = Arc::default();
+ let closed = Arc::new(AtomicBool::new(false));
+ let stderr_tail = Arc::new(StdMutex::new(String::new()));
+
+ let reader = {
+ let (pending, closed, stdin) = (pending.clone(), closed.clone(), stdin.clone());
+ tokio::spawn(async move {
+ let mut lines = BufReader::new(stdout).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let Ok(msg) = serde_json::from_str::<Value>(line.trim()) else {
+ tracing::debug!("ignoring non-JSON line from MCP server");
+ continue;
+ };
+ if let Some(id) = response_id(&msg) {
+ if let Some(tx) = pending.lock().ok().and_then(|mut p| p.remove(&id)) {
+ let _ = tx.send(msg);
+ }
+ } else if let (Some(method), Some(id)) = (msg["method"].as_str(), msg.get("id")) {
+ // Requests from the server: answer ping, decline the rest
+ let reply = if method == "ping" {
+ json!({"jsonrpc": "2.0", "id": id, "result": {}})
+ } else {
+ json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not supported by kwnt"}})
+ };
+ let _ = write_line(&stdin, &reply).await;
+ }
+ }
+ closed.store(true, Ordering::SeqCst);
+ // Dropping the senders wakes every waiting request with `Closed`
+ if let Ok(mut p) = pending.lock() {
+ p.clear();
+ }
+ })
+ };
+ let stderr_task = {
+ let tail = stderr_tail.clone();
+ tokio::spawn(async move {
+ let mut buf = [0u8; 1024];
+ while let Ok(n) = stderr.read(&mut buf).await {
+ if n == 0 {
+ break;
+ }
+ if let Ok(mut t) = tail.lock() {
+ t.push_str(&String::from_utf8_lossy(&buf[..n]));
+ if t.len() > STDERR_TAIL_BYTES {
+ let mut cut = t.len() - STDERR_TAIL_BYTES;
+ while !t.is_char_boundary(cut) {
+ cut += 1;
+ }
+ t.drain(..cut);
+ }
+ }
+ }
+ })
+ };
+
+ Ok(StdioTransport {
+ child: Mutex::new(Some(child)),
+ stdin,
+ pending,
+ closed,
+ stderr_tail,
+ tasks: vec![reader, stderr_task],
+ })
+ }
+
+ fn http_transport(server: &McpServer) -> Result<HttpTransport, McpError> {
+ let url = server.url.clone().ok_or_else(|| McpError::Spawn("no url".into()))?;
+ let mut headers = reqwest::header::HeaderMap::new();
+ for (k, v) in &server.headers {
+ let name = reqwest::header::HeaderName::from_bytes(k.as_bytes())
+ .map_err(|_| McpError::Spawn(format!("invalid header name '{k}'")))?;
+ let mut value = reqwest::header::HeaderValue::from_str(v)
+ .map_err(|_| McpError::Spawn(format!("invalid value for header '{k}'")))?;
+ value.set_sensitive(true);
+ headers.insert(name, value);
+ }
+ let client = reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .map_err(|e| McpError::Spawn(e.to_string()))?;
+ Ok(HttpTransport {
+ client,
+ url,
+ headers,
+ session_id: StdMutex::new(None),
+ protocol_version: StdMutex::new(None),
+ })
+ }
+
+ async fn handshake(&mut self) -> Result<(), McpError> {
+ let result = self
+ .request(
+ "initialize",
+ json!({
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "kwnt", "version": env!("CARGO_PKG_VERSION")},
+ }),
+ )
+ .await?;
+ self.server_info = result.get("serverInfo").cloned().unwrap_or(Value::Null);
+ if let Transport::Http(ref http) = self.transport {
+ let version = result["protocolVersion"].as_str().unwrap_or(PROTOCOL_VERSION).to_string();
+ *http.protocol_version.lock().unwrap() = Some(version);
+ }
+ self.notify("notifications/initialized", json!({})).await
+ }
+
+ /// The last few KB the server wrote to stderr (stdio only).
+ pub fn stderr_tail(&self) -> String {
+ match &self.transport {
+ Transport::Stdio(s) => s.stderr_tail.lock().map(|t| t.clone()).unwrap_or_default(),
+ Transport::Http(_) => String::new(),
+ }
+ }
+
+ pub async fn list_tools(&self) -> Result<Vec<McpTool>, McpError> {
+ let mut tools = Vec::new();
+ let mut cursor: Option<String> = None;
+ for _ in 0..MAX_TOOL_PAGES {
+ let params = match &cursor {
+ Some(c) => json!({"cursor": c}),
+ None => json!({}),
+ };
+ let result = self.request("tools/list", params).await?;
+ let page = result["tools"].as_array().ok_or_else(|| McpError::Protocol("tools/list without tools".into()))?;
+ for t in page {
+ let Some(name) = t["name"].as_str() else { continue };
+ tools.push(McpTool {
+ name: name.to_string(),
+ description: t["description"].as_str().map(str::to_string),
+ input_schema: t.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object"})),
+ });
+ }
+ cursor = result["nextCursor"].as_str().map(str::to_string);
+ if cursor.is_none() {
+ break;
+ }
+ }
+ Ok(tools)
+ }
+
+ pub async fn call_tool(&self, name: &str, arguments: Value) -> Result<ToolCallResult, McpError> {
+ let args = if arguments.is_object() { arguments } else { json!({}) };
+ let result = self.request("tools/call", json!({"name": name, "arguments": args})).await?;
+ Ok(ToolCallResult {
+ text: result_text(&result),
+ is_error: result["isError"].as_bool().unwrap_or(false),
+ })
+ }
+
+ async fn request(&self, method: &str, params: Value) -> Result<Value, McpError> {
+ let id = self.next_id.fetch_add(1, Ordering::SeqCst);
+ let msg = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
+ let response = match &self.transport {
+ Transport::Stdio(s) => self.stdio_request(s, id, method, &msg).await?,
+ Transport::Http(h) => {
+ tokio::time::timeout(self.timeout, self.http_post(h, &msg, Some(id)))
+ .await
+ .map_err(|_| McpError::Timeout(self.timeout.as_secs(), method.to_string()))??
+ .ok_or_else(|| McpError::Protocol(format!("no response to {method}")))?
+ }
+ };
+ if let Some(err) = response.get("error") {
+ return Err(McpError::Rpc {
+ code: err["code"].as_i64().unwrap_or(0),
+ message: err["message"].as_str().unwrap_or("unknown error").to_string(),
+ });
+ }
+ Ok(response.get("result").cloned().unwrap_or(Value::Null))
+ }
+
+ async fn stdio_request(&self, s: &StdioTransport, id: i64, method: &str, msg: &Value) -> Result<Value, McpError> {
+ if s.closed.load(Ordering::SeqCst) {
+ return Err(McpError::Closed);
+ }
+ let (tx, rx) = oneshot::channel();
+ s.pending.lock().unwrap().insert(id, tx);
+ if let Err(e) = write_line(&s.stdin, msg).await {
+ s.pending.lock().unwrap().remove(&id);
+ return Err(e);
+ }
+ match tokio::time::timeout(self.timeout, rx).await {
+ Ok(Ok(response)) => Ok(response),
+ Ok(Err(_)) => Err(McpError::Closed),
+ Err(_) => {
+ s.pending.lock().unwrap().remove(&id);
+ let cancel = json!({"jsonrpc": "2.0", "method": "notifications/cancelled",
+ "params": {"requestId": id, "reason": "timeout"}});
+ let _ = write_line(&s.stdin, &cancel).await;
+ Err(McpError::Timeout(self.timeout.as_secs(), method.to_string()))
+ }
+ }
+ }
+
+ async fn notify(&self, method: &str, params: Value) -> Result<(), McpError> {
+ let msg = json!({"jsonrpc": "2.0", "method": method, "params": params});
+ match &self.transport {
+ Transport::Stdio(s) => write_line(&s.stdin, &msg).await,
+ Transport::Http(h) => tokio::time::timeout(self.timeout, self.http_post(h, &msg, None))
+ .await
+ .map_err(|_| McpError::Timeout(self.timeout.as_secs(), method.to_string()))?
+ .map(|_| ()),
+ }
+ }
+
+ /// POSTs one message. For requests, returns the matching response from a JSON or SSE body.
+ async fn http_post(&self, h: &HttpTransport, msg: &Value, id: Option<i64>) -> Result<Option<Value>, McpError> {
+ let mut req = h
+ .client
+ .post(&h.url)
+ .headers(h.headers.clone())
+ .header("Accept", "application/json, text/event-stream")
+ .json(msg);
+ if let Some(sid) = h.session_id.lock().unwrap().clone() {
+ req = req.header("Mcp-Session-Id", sid);
+ }
+ if let Some(v) = h.protocol_version.lock().unwrap().clone() {
+ req = req.header("MCP-Protocol-Version", v);
+ }
+ let resp = req.send().await.map_err(|e| McpError::Transport(e.without_url().to_string()))?;
+ let status = resp.status();
+ if !status.is_success() {
+ return Err(McpError::Transport(format!("HTTP {status}")));
+ }
+ if let Some(sid) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {
+ *h.session_id.lock().unwrap() = Some(sid.to_string());
+ }
+ let Some(id) = id else {
+ return Ok(None);
+ };
+ let content_type = resp
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+
+ if content_type.starts_with("text/event-stream") {
+ let mut stream = resp.bytes_stream();
+ let mut buf = String::new();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|e| McpError::Transport(e.without_url().to_string()))?;
+ buf.push_str(&String::from_utf8_lossy(&chunk).replace("\r\n", "\n"));
+ while let Some(end) = buf.find("\n\n") {
+ let event: String = buf.drain(..end + 2).collect();
+ let data = event
+ .lines()
+ .filter_map(|l| l.strip_prefix("data:"))
+ .map(|d| d.strip_prefix(' ').unwrap_or(d))
+ .collect::<Vec<_>>()
+ .join("\n");
+ if let Ok(msg) = serde_json::from_str::<Value>(&data) {
+ if response_id(&msg) == Some(id) {
+ return Ok(Some(msg));
+ }
+ }
+ }
+ }
+ return Err(McpError::Protocol("event stream ended before the response".into()));
+ }
+
+ let body: Value = resp.json().await.map_err(|e| McpError::Protocol(e.without_url().to_string()))?;
+ let found = match body {
+ Value::Array(items) => items.into_iter().find(|m| response_id(m) == Some(id)),
+ single => (response_id(&single) == Some(id)).then_some(single),
+ };
+ found.map(Some).ok_or_else(|| McpError::Protocol("response id does not match".into()))
+ }
+
+ /// Ends the session: closes stdin and waits briefly, then kills the process (stdio), or
+ /// deletes the session (HTTP). Always safe to call.
+ pub async fn shutdown(&mut self) {
+ match &mut self.transport {
+ Transport::Stdio(s) => {
+ s.stdin.lock().await.take();
+ if let Some(mut child) = s.child.lock().await.take() {
+ if tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() {
+ let _ = child.start_kill();
+ let _ = child.wait().await;
+ }
+ }
+ // Let the readers drain what the process wrote before it exited
+ for mut task in s.tasks.drain(..) {
+ if tokio::time::timeout(Duration::from_millis(500), &mut task).await.is_err() {
+ task.abort();
+ }
+ }
+ }
+ Transport::Http(h) => {
+ let sid = h.session_id.lock().unwrap().take();
+ if let Some(sid) = sid {
+ let req = h.client.delete(&h.url).headers(h.headers.clone()).header("Mcp-Session-Id", sid);
+ let _ = tokio::time::timeout(Duration::from_secs(2), req.send()).await;
+ }
+ }
+ }
+ }
+}
+
+impl Drop for StdioTransport {
+ fn drop(&mut self) {
+ // `kill_on_drop` stops the process; also stop the reader tasks
+ for task in &self.tasks {
+ task.abort();
+ }
+ }
+}
diff --git a/src/mcp/echo_server.rs b/src/mcp/echo_server.rs
new file mode 100644
index 00000000..4f0a83b4
--- /dev/null
+++ b/src/mcp/echo_server.rs
@@ -0,0 +1,85 @@
+//! A tiny stdio MCP server, run with the hidden `kwnt mcp-echo-server` subcommand. It exists so
+//! tests and smoke checks have a real MCP server without Python, Node or network access.
+//!
+//! Tools: `echo {text}`, `add {a, b}`, `sleep {ms}`, `env {name}` (reads its own environment)
+//! and `crash` (exits mid-call).
+
+use serde_json::{json, Value};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+fn tools() -> Value {
+ let obj = |props: Value, required: Value| json!({"type": "object", "properties": props, "required": required});
+ json!([
+ {"name": "echo", "description": "Returns the given text unchanged.",
+ "inputSchema": obj(json!({"text": {"type": "string"}}), json!(["text"]))},
+ {"name": "add", "description": "Adds two numbers.",
+ "inputSchema": obj(json!({"a": {"type": "number"}, "b": {"type": "number"}}), json!(["a", "b"]))},
+ {"name": "sleep", "description": "Waits for the given milliseconds, then answers.",
+ "inputSchema": obj(json!({"ms": {"type": "integer"}}), json!(["ms"]))},
+ {"name": "env", "description": "Returns the value of one of this server's environment variables.",
+ "inputSchema": obj(json!({"name": {"type": "string"}}), json!(["name"]))},
+ {"name": "crash", "description": "Exits the server without answering.",
+ "inputSchema": obj(json!({}), json!([]))},
+ ])
+}
+
+fn text_result(text: String, is_error: bool) -> Value {
+ json!({"content": [{"type": "text", "text": text}], "isError": is_error})
+}
+
+async fn call(name: &str, args: &Value) -> Value {
+ match name {
+ "echo" => text_result(args["text"].as_str().unwrap_or("").to_string(), false),
+ "add" => {
+ let sum = args["a"].as_f64().unwrap_or(0.0) + args["b"].as_f64().unwrap_or(0.0);
+ text_result(sum.to_string(), false)
+ }
+ "sleep" => {
+ let ms = args["ms"].as_u64().unwrap_or(0);
+ tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
+ text_result(format!("slept {ms} ms"), false)
+ }
+ "env" => {
+ let var = args["name"].as_str().unwrap_or("");
+ match std::env::var(var) {
+ Ok(v) => text_result(v, false),
+ Err(_) => text_result(format!("{var} is not set"), true),
+ }
+ }
+ "crash" => {
+ eprintln!("mcp-echo-server: crashing on request");
+ std::process::exit(3);
+ }
+ other => text_result(format!("unknown tool {other}"), true),
+ }
+}
+
+/// Serves MCP on stdin/stdout until stdin closes.
+pub async fn run_stdio() -> std::io::Result<()> {
+ let mut lines = BufReader::new(tokio::io::stdin()).lines();
+ let mut stdout = tokio::io::stdout();
+ while let Some(line) = lines.next_line().await? {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
+ let Some(id) = msg.get("id").cloned() else { continue }; // notifications need no answer
+ let result = match msg["method"].as_str().unwrap_or("") {
+ "initialize" => json!({
+ "protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or(super::client::PROTOCOL_VERSION),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "kwnt-echo", "version": env!("CARGO_PKG_VERSION")},
+ }),
+ "ping" => json!({}),
+ "tools/list" => json!({"tools": tools()}),
+ "tools/call" => call(msg["params"]["name"].as_str().unwrap_or(""), &msg["params"]["arguments"]).await,
+ _ => {
+ let err = json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}});
+ stdout.write_all(format!("{err}\n").as_bytes()).await?;
+ stdout.flush().await?;
+ continue;
+ }
+ };
+ let reply = json!({"jsonrpc": "2.0", "id": id, "result": result});
+ stdout.write_all(format!("{reply}\n").as_bytes()).await?;
+ stdout.flush().await?;
+ }
+ Ok(())
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
new file mode 100644
index 00000000..bcda9e89
--- /dev/null
+++ b/src/mcp/mod.rs
@@ -0,0 +1,361 @@
+//! Model Context Protocol support: the server registry's validation and secret masking, a small
+//! MCP client (stdio + streamable HTTP), and the per-turn context drivers use to offer MCP tools.
+
+pub mod client;
+pub mod echo_server;
+
+pub use client::{McpClient, McpError, McpTool};
+
+use crate::db::models::McpServer;
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+/// Shown in place of every secret value; sending it back on update keeps the stored value.
+pub const SECRET_MASK: &str = "********";
+/// Server name kwnt uses for its own permission endpoint in agent CLI configs.
+pub const RESERVED_SERVER_NAME: &str = "kwnt";
+pub const DEFAULT_TIMEOUT_SECS: i64 = 30;
+pub const DEFAULT_MAX_TOOL_ITERATIONS: usize = 8;
+/// Longest tool result kept in a message's `tool_calls` record.
+pub const RECORD_RESULT_MAX_CHARS: usize = 4000;
+
+/// API representation of a server: secrets replaced by [`SECRET_MASK`].
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct McpServerView {
+ pub id: String,
+ pub name: String,
+ pub transport: String,
+ pub command: Option<String>,
+ pub args: Vec<String>,
+ pub url: Option<String>,
+ pub env: BTreeMap<String, String>,
+ pub headers: BTreeMap<String, String>,
+ pub enabled: bool,
+ pub timeout_secs: i64,
+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl From<&McpServer> for McpServerView {
+ fn from(s: &McpServer) -> Self {
+ let mask = |m: &BTreeMap<String, String>| m.keys().map(|k| (k.clone(), SECRET_MASK.to_string())).collect();
+ Self {
+ id: s.id.clone(),
+ name: s.name.clone(),
+ transport: s.transport.clone(),
+ command: s.command.clone(),
+ args: s.args.clone(),
+ url: s.url.clone(),
+ env: mask(&s.env),
+ headers: mask(&s.headers),
+ enabled: s.enabled,
+ timeout_secs: s.timeout_secs,
+ created_at: s.created_at,
+ }
+ }
+}
+
+/// Body of create and update requests.
+#[derive(Debug, Clone, Deserialize)]
+pub struct McpServerInput {
+ pub name: String,
+ pub transport: String,
+ #[serde(default)]
+ pub command: Option<String>,
+ #[serde(default)]
+ pub args: Option<Vec<String>>,
+ #[serde(default)]
+ pub url: Option<String>,
+ #[serde(default)]
+ pub env: Option<BTreeMap<String, String>>,
+ #[serde(default)]
+ pub headers: Option<BTreeMap<String, String>>,
+ #[serde(default)]
+ pub enabled: Option<bool>,
+ #[serde(default)]
+ pub timeout_secs: Option<i64>,
+}
+
+fn valid_server_name(name: &str) -> bool {
+ let first_ok = name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
+ first_ok
+ && name.len() <= 48
+ && !name.contains("__")
+ && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+fn valid_env_key(key: &str) -> bool {
+ let first_ok = key.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
+ first_ok && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
+}
+
+fn valid_header_name(name: &str) -> bool {
+ !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c))
+}
+
+/// Applies the masking rules: a masked value keeps the stored one, a missing map keeps them all.
+fn merge_secrets(
+ incoming: Option<BTreeMap<String, String>>,
+ existing: Option<&BTreeMap<String, String>>,
+ what: &str,
+) -> Result<BTreeMap<String, String>, String> {
+ let Some(incoming) = incoming else {
+ return Ok(existing.cloned().unwrap_or_default());
+ };
+ let mut merged = BTreeMap::new();
+ for (key, value) in incoming {
+ if value == SECRET_MASK {
+ match existing.and_then(|e| e.get(&key)) {
+ Some(stored) => merged.insert(key, stored.clone()),
+ None => return Err(format!("{what} '{key}' has no stored value to keep; send the real value")),
+ };
+ } else {
+ merged.insert(key, value);
+ }
+ }
+ Ok(merged)
+}
+
+/// Validates a create/update body and turns it into a server, merging masked secrets with
+/// `existing` on update. The returned server keeps `existing`'s id and creation time.
+pub fn build_server(input: McpServerInput, existing: Option<&McpServer>) -> Result<McpServer, String> {
+ let name = input.name.trim().to_string();
+ if !valid_server_name(&name) {
+ return Err("name must be 1-48 characters of letters, digits, '_' or '-', start with a letter or digit and not contain '__'".into());
+ }
+ if name.eq_ignore_ascii_case(RESERVED_SERVER_NAME) {
+ return Err(format!("name '{RESERVED_SERVER_NAME}' is reserved"));
+ }
+ let timeout_secs = input.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS);
+ if !(1..=600).contains(&timeout_secs) {
+ return Err("timeout_secs must be between 1 and 600".into());
+ }
+ let env = merge_secrets(input.env, existing.map(|e| &e.env), "env")?;
+ let headers = merge_secrets(input.headers, existing.map(|e| &e.headers), "header")?;
+ let command = input.command.map(|c| c.trim().to_string()).filter(|c| !c.is_empty());
+ let url = input.url.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
+ let args = input.args.unwrap_or_default();
+
+ match input.transport.as_str() {
+ "stdio" => {
+ if command.is_none() {
+ return Err("stdio servers need a command".into());
+ }
+ if url.is_some() {
+ return Err("stdio servers take no url".into());
+ }
+ if !headers.is_empty() {
+ return Err("headers only apply to http servers".into());
+ }
+ if let Some(bad) = env.keys().find(|k| !valid_env_key(k)) {
+ return Err(format!("invalid env variable name '{bad}'"));
+ }
+ }
+ "http" => {
+ let Some(ref u) = url else {
+ return Err("http servers need a url".into());
+ };
+ match reqwest::Url::parse(u) {
+ Ok(parsed) if matches!(parsed.scheme(), "http" | "https") && parsed.host().is_some() => {}
+ _ => return Err("url must be an http:// or https:// address".into()),
+ }
+ if command.is_some() || !args.is_empty() {
+ return Err("http servers take no command or args".into());
+ }
+ if !env.is_empty() {
+ return Err("env only applies to stdio servers".into());
+ }
+ if let Some(bad) = headers.keys().find(|k| !valid_header_name(k)) {
+ return Err(format!("invalid header name '{bad}'"));
+ }
+ }
+ _ => return Err("transport must be 'stdio' or 'http'".into()),
+ }
+
+ Ok(McpServer {
+ id: existing.map(|e| e.id.clone()).unwrap_or_default(),
+ name,
+ transport: input.transport,
+ command,
+ args,
+ url,
+ env,
+ headers,
+ enabled: input.enabled.unwrap_or(true),
+ timeout_secs,
+ created_at: existing.and_then(|e| e.created_at),
+ })
+}
+
+/// Replaces every non-empty secret in `text` with [`SECRET_MASK`].
+pub fn redact(text: &str, secrets: &[String]) -> String {
+ let mut out = text.to_string();
+ let mut sorted: Vec<&String> = secrets.iter().filter(|s| !s.is_empty()).collect();
+ // Longest first, so a secret containing another is masked whole
+ sorted.sort_by_key(|s| std::cmp::Reverse(s.len()));
+ for secret in sorted {
+ out = out.replace(secret.as_str(), SECRET_MASK);
+ }
+ out
+}
+
+/// Cuts `text` to at most `max` characters, marking the cut.
+pub fn truncate_text(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((idx, _)) => format!("{}… [truncated]", &text[..idx]),
+ None => text.to_string(),
+ }
+}
+
+/// `mcp__<server>__<tool>`, the name agents see for an MCP tool.
+pub fn namespaced_tool_name(server: &str, tool: &str) -> String {
+ format!("mcp__{server}__{tool}")
+}
+
+/// Splits `mcp__<server>__<tool>`; server names cannot contain `__`, so the first split is right.
+pub fn split_tool_name(name: &str) -> Option<(&str, &str)> {
+ let rest = name.strip_prefix("mcp__")?;
+ let (server, tool) = rest.split_once("__")?;
+ (!server.is_empty() && !tool.is_empty()).then_some((server, tool))
+}
+
+/// One tool call waiting for the user's approval.
+#[derive(Debug, Clone, Serialize)]
+pub struct ToolApprovalRequest {
+ pub kwant_id: String,
+ pub kwant_name: String,
+ pub turn_id: String,
+ /// Namespaced name, e.g. `mcp__github__create_issue`.
+ pub tool_name: String,
+ pub server: String,
+ pub tool: String,
+ pub arguments: Value,
+}
+
+/// Decides whether an MCP tool call may run. The server implements it with the permission broker.
+#[async_trait]
+pub trait ToolApprover: Send + Sync {
+ async fn approve(&self, request: ToolApprovalRequest) -> bool;
+}
+
+/// Approves or denies everything; for tests and tooling.
+pub struct FixedApprover(pub bool);
+
+#[async_trait]
+impl ToolApprover for FixedApprover {
+ async fn approve(&self, _request: ToolApprovalRequest) -> bool {
+ self.0
+ }
+}
+
+/// What a driver needs to offer MCP tools on one turn. Only set when the kwant has servers.
+#[derive(Clone)]
+pub struct McpTurnContext {
+ /// The kwant's enabled servers, secrets included.
+ pub servers: Vec<McpServer>,
+ pub approver: Arc<dyn ToolApprover>,
+ /// Private directory for per-turn agent CLI config files.
+ pub config_dir: PathBuf,
+ /// kwnt's permission-prompt MCP endpoint for this turn (claude CLI only).
+ pub permission_url: Option<String>,
+ pub max_tool_iterations: usize,
+ /// Tool call records for the reply's `tool_calls` field; drivers and the permission endpoint append.
+ pub records: Arc<Mutex<Vec<Value>>>,
+}
+
+impl McpTurnContext {
+ pub fn record(&self, record: Value) {
+ if let Ok(mut r) = self.records.lock() {
+ r.push(record);
+ }
+ }
+
+ pub fn take_records(&self) -> Vec<Value> {
+ self.records.lock().map(|mut r| std::mem::take(&mut *r)).unwrap_or_default()
+ }
+
+ pub fn secret_values(&self) -> Vec<String> {
+ self.servers.iter().flat_map(|s| s.secret_values()).collect()
+ }
+}
+
+impl std::fmt::Debug for McpTurnContext {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("McpTurnContext")
+ .field("servers", &self.servers)
+ .field("config_dir", &self.config_dir)
+ .field("permission_url", &self.permission_url.as_ref().map(|_| "<set>"))
+ .field("max_tool_iterations", &self.max_tool_iterations)
+ .finish()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn input(json: Value) -> McpServerInput {
+ serde_json::from_value(json).unwrap()
+ }
+
+ #[test]
+ fn validates_names_and_transports() {
+ assert!(build_server(input(serde_json::json!({"name": "ok-name_1", "transport": "stdio", "command": "x"})), None).is_ok());
+ for bad in ["", "-lead", "a__b", "has space", "kwnt", "KWNT", &"x".repeat(49)] {
+ assert!(build_server(input(serde_json::json!({"name": bad, "transport": "stdio", "command": "x"})), None).is_err(), "{bad}");
+ }
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio"})), None).is_err());
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "http", "url": "ftp://x"})), None).is_err());
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "http", "url": "https://x.dev/mcp", "command": "y"})), None).is_err());
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "ws", "url": "https://x"})), None).is_err());
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio", "command": "x", "env": {"1BAD": "v"}})), None).is_err());
+ assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio", "command": "x", "timeout_secs": 0})), None).is_err());
+ }
+
+ #[test]
+ fn masks_and_merges_secrets() {
+ let created = build_server(
+ input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"TOKEN": "s3cret", "OTHER": "o"}})),
+ None,
+ )
+ .unwrap();
+ let view = McpServerView::from(&created);
+ assert_eq!(view.env.get("TOKEN").unwrap(), SECRET_MASK);
+ assert!(!serde_json::to_string(&view).unwrap().contains("s3cret"));
+ assert!(!format!("{created:?}").contains("s3cret"));
+
+ // Mask keeps, new value replaces, omitted key deletes
+ let updated = build_server(
+ input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"TOKEN": SECRET_MASK, "NEW": "n"}})),
+ Some(&created),
+ )
+ .unwrap();
+ assert_eq!(updated.env.get("TOKEN").unwrap(), "s3cret");
+ assert_eq!(updated.env.get("NEW").unwrap(), "n");
+ assert!(!updated.env.contains_key("OTHER"));
+
+ // Omitted map keeps everything
+ let kept = build_server(input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x"})), Some(&created)).unwrap();
+ assert_eq!(kept.env, created.env);
+
+ // A mask for a key that was never stored is an error, not an empty secret
+ assert!(build_server(
+ input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"NOPE": SECRET_MASK}})),
+ Some(&created)
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn redacts_and_splits_names() {
+ assert_eq!(redact("token=abc123 and abc", &["abc123".into(), "".into()]), "token=******** and abc");
+ assert_eq!(split_tool_name("mcp__gh__create_issue"), Some(("gh", "create_issue")));
+ assert_eq!(split_tool_name("mcp__gh__a__b"), Some(("gh", "a__b")));
+ assert_eq!(split_tool_name("Bash"), None);
+ assert_eq!(namespaced_tool_name("gh", "x"), "mcp__gh__x");
+ assert_eq!(truncate_text("héllo", 2), "hé… [truncated]");
+ }
+}
diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rs
new file mode 100644
index 00000000..d55b0deb
--- /dev/null
+++ b/src/server/mcp_routes.rs
@@ -0,0 +1,140 @@
+//! MCP server registry and per-kwant assignment endpoints. Contract: docs/mcp-api.md.
+
+use super::AppState;
+use crate::db::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() })))
+}
+
+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, "an MCP server with that name already exists");
+ }
+ }
+ tracing::warn!(error = %e, "MCP registry database error");
+ err(StatusCode::INTERNAL_SERVER_ERROR, "database error")
+}
+
+pub async fn list_servers(State(state): State<AppState>) -> ApiResult<Vec<McpServerView>> {
+ let servers = state.db.list_mcp_servers().await.map_err(db_err)?;
+ Ok(Json(servers.iter().map(McpServerView::from).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(McpServerView::from(&s))),
+ None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),
+ }
+}
+
+pub async fn create_server(State(state): State<AppState>, Json(input): Json<McpServerInput>) -> ApiResult<McpServerView> {
+ let server = mcp::build_server(input, None).map_err(|m| err(StatusCode::BAD_REQUEST, m))?;
+ let created = state.db.create_mcp_server(&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))?;
+ match state.db.update_mcp_server(&server).await.map_err(db_err)? {
+ Some(s) => Ok(Json(McpServerView::from(&s))),
+ 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)? {
+ Ok(Json(json!({ "status": "deleted" })))
+ } else {
+ Err(err(StatusCode::NOT_FOUND, "MCP server not found"))
+ }
+}
+
+/// Connects with the stored config, lists the tools and disconnects. Errors are redacted.
+pub async fn test_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {
+ let server = state
+ .db
+ .get_mcp_server(&id)
+ .await
+ .map_err(db_err)?
+ .ok_or_else(|| err(StatusCode::NOT_FOUND, "MCP server not found"))?;
+ let secrets = server.secret_values();
+ let start = Instant::now();
+ let cwd = state.config.data_dir.join("workspace");
+
+ let mut outcome = 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;
+ match tools {
+ Ok(tools) => json!({ "ok": true, "server_info": client.server_info, "tools": tools }),
+ Err(e) => json!({ "ok": false, "error": mcp::redact(&e.to_string(), &secrets),
+ "stderr_tail": mcp::redact(&stderr_tail, &secrets) }),
+ }
+ }
+ Err(e) => {
+ let stderr_tail = match e {
+ McpError::Startup { ref stderr_tail, .. } => stderr_tail.clone(),
+ _ => String::new(),
+ };
+ 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);
+ Ok(Json(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, "kwant 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> {
+ if state.db.get_kwant(&kwant_id).await.map_err(db_err)?.is_none() {
+ return Err(err(StatusCode::NOT_FOUND, "kwant not found"));
+ }
+ let known: Vec<String> = state.db.list_mcp_servers().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 })))
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 97af3330..5cf6efbf 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -2,6 +2,7 @@ pub mod discussion;
pub mod routes;
pub mod sse;
pub mod browser_stream;
+pub mod mcp_routes;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -98,6 +99,13 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/sandbox/:team_id/act", post(routes::act_sandbox))
.route("/api/sandbox/:team_id/passwords", get(routes::get_saved_passwords).post(routes::save_password))
.route("/api/sandbox/:team_id/passwords/:id", delete(routes::delete_password))
+ .route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server))
+ .route(
+ "/api/mcp/servers/:id",
+ get(mcp_routes::get_server).put(mcp_routes::update_server).delete(mcp_routes::delete_server),
+ )
+ .route("/api/mcp/servers/:id/test", post(mcp_routes::test_server))
+ .route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(cors)
diff --git a/tests/mcp_test.rs b/tests/mcp_test.rs
new file mode 100644
index 00000000..74963897
--- /dev/null
+++ b/tests/mcp_test.rs
@@ -0,0 +1,205 @@
+use axum::{
+ body::Body,
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::McpServer, Database},
+ mcp::{McpClient, McpError, SECRET_MASK},
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::time::{Duration, Instant};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const KWNT: &str = env!("CARGO_BIN_EXE_kwnt");
+
+fn echo_server(timeout_secs: i64) -> McpServer {
+ McpServer {
+ id: "s1".into(),
+ name: "echo".into(),
+ transport: "stdio".into(),
+ command: Some(KWNT.into()),
+ args: vec!["mcp-echo-server".into()],
+ url: None,
+ env: BTreeMap::from([("ECHO_SECRET".to_string(), "hunter2-secret".to_string())]),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs,
+ created_at: None,
+ }
+}
+
+async fn app() -> (Router, Database, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db.clone(),
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state), db, tmp)
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty))
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+#[tokio::test]
+async fn stdio_client_lists_and_calls_tools() {
+ let mut client = McpClient::connect(&echo_server(10), None).await.unwrap();
+ assert_eq!(client.server_info["name"], "kwnt-echo");
+
+ let tools = client.list_tools().await.unwrap();
+ let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
+ assert_eq!(names, ["echo", "add", "sleep", "env", "crash"]);
+ assert_eq!(tools[0].input_schema["required"], json!(["text"]));
+
+ let out = client.call_tool("echo", json!({"text": "hello mcp"})).await.unwrap();
+ assert_eq!(out.text, "hello mcp");
+ assert!(!out.is_error);
+ assert_eq!(client.call_tool("add", json!({"a": 2, "b": 3})).await.unwrap().text, "5");
+ // Configured env reaches the server; kwnt's own environment does not
+ assert_eq!(client.call_tool("env", json!({"name": "ECHO_SECRET"})).await.unwrap().text, "hunter2-secret");
+ std::env::set_var("KWNT_PRIVATE_TEST_VAR", "leak");
+ let mut fresh = McpClient::connect(&echo_server(10), None).await.unwrap();
+ assert!(fresh.call_tool("env", json!({"name": "KWNT_PRIVATE_TEST_VAR"})).await.unwrap().is_error);
+ fresh.shutdown().await;
+
+ client.shutdown().await;
+ // A shut-down client fails fast instead of hanging
+ assert!(client.call_tool("echo", json!({"text": "x"})).await.is_err());
+}
+
+#[tokio::test]
+async fn server_crash_mid_call_fails_fast() {
+ let mut client = McpClient::connect(&echo_server(30), None).await.unwrap();
+ let start = Instant::now();
+ let err = client.call_tool("crash", json!({})).await.unwrap_err();
+ assert!(matches!(err, McpError::Closed), "{err:?}");
+ assert!(start.elapsed() < Duration::from_secs(5), "crash should not wait for the timeout");
+ assert!(client.stderr_tail().contains("crashing on request"));
+ client.shutdown().await;
+}
+
+#[tokio::test]
+async fn slow_tool_times_out_and_server_is_stopped() {
+ let mut client = McpClient::connect(&echo_server(1), None).await.unwrap();
+ let start = Instant::now();
+ let err = client.call_tool("sleep", json!({"ms": 10_000})).await.unwrap_err();
+ assert!(matches!(err, McpError::Timeout(1, _)), "{err:?}");
+ assert!(start.elapsed() < Duration::from_secs(3));
+ let start = Instant::now();
+ client.shutdown().await;
+ assert!(start.elapsed() < Duration::from_secs(4), "shutdown must not wait for the sleeping tool");
+}
+
+#[tokio::test]
+async fn missing_command_is_a_startup_error() {
+ let mut server = echo_server(5);
+ server.command = Some("/nonexistent/kwnt-mcp-binary".into());
+ assert!(matches!(McpClient::connect(&server, None).await, Err(McpError::Spawn(_))));
+}
+
+#[tokio::test]
+async fn registry_crud_masks_secrets() {
+ let (app, db, _tmp) = app().await;
+
+ let body = json!({"name": "echo", "transport": "stdio", "command": KWNT, "args": ["mcp-echo-server"],
+ "env": {"ECHO_SECRET": "hunter2-secret"}});
+ let (status, created) = call(&app, "POST", "/api/mcp/servers", Some(body.clone())).await;
+ assert_eq!(status, StatusCode::OK, "{created}");
+ assert_eq!(created["env"]["ECHO_SECRET"], SECRET_MASK);
+ assert_eq!(created["enabled"], true);
+ assert_eq!(created["timeout_secs"], 30);
+ let id = created["id"].as_str().unwrap().to_string();
+
+ let (status, _) = call(&app, "POST", "/api/mcp/servers", Some(body)).await;
+ assert_eq!(status, StatusCode::CONFLICT);
+ let (status, e) = call(&app, "POST", "/api/mcp/servers", Some(json!({"name": "x", "transport": "http"}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert!(e["error"].as_str().unwrap().contains("url"));
+
+ let (_, list) = call(&app, "GET", "/api/mcp/servers", None).await;
+ assert!(!list.to_string().contains("hunter2"));
+ let (_, one) = call(&app, "GET", &format!("/api/mcp/servers/{id}"), None).await;
+ assert_eq!(one["env"]["ECHO_SECRET"], SECRET_MASK);
+
+ // Sending the mask back keeps the stored secret
+ let update = json!({"name": "echo2", "transport": "stdio", "command": KWNT, "args": ["mcp-echo-server"],
+ "env": {"ECHO_SECRET": SECRET_MASK, "EXTRA": "e"}, "enabled": false});
+ let (status, updated) = call(&app, "PUT", &format!("/api/mcp/servers/{id}"), Some(update)).await;
+ assert_eq!(status, StatusCode::OK, "{updated}");
+ assert_eq!(updated["name"], "echo2");
+ assert_eq!(updated["enabled"], false);
+ let stored = db.get_mcp_server(&id).await.unwrap().unwrap();
+ assert_eq!(stored.env["ECHO_SECRET"], "hunter2-secret");
+ assert_eq!(stored.env["EXTRA"], "e");
+
+ let (status, _) = call(&app, "GET", "/api/mcp/servers/nope", None).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+
+ // Assignment: only enabled servers are active for the kwant
+ let kwant_id = db.list_kwants().await.unwrap()[0].id.clone();
+ let uri = format!("/api/kwants/{kwant_id}/mcp-servers");
+ let (status, _) = call(&app, "PUT", &uri, Some(json!({"server_ids": ["nope"]}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ let (status, assigned) = call(&app, "PUT", &uri, Some(json!({"server_ids": [id]}))).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(assigned["server_ids"], json!([id]));
+ assert!(db.list_active_mcp_servers_for_kwant(&kwant_id).await.unwrap().is_empty());
+ let (status, _) = call(&app, "GET", "/api/kwants/nope/mcp-servers", None).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+
+ let (status, _) = call(&app, "DELETE", &format!("/api/mcp/servers/{id}"), None).await;
+ assert_eq!(status, StatusCode::OK);
+ let (_, after) = call(&app, "GET", &uri, None).await;
+ assert_eq!(after["server_ids"], json!([]));
+ let (status, _) = call(&app, "DELETE", &format!("/api/mcp/servers/{id}"), None).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn test_endpoint_lists_tools_and_redacts_errors() {
+ let (app, _db, _tmp) = app().await;
+
+ let (_, ok_server) = call(&app, "POST", "/api/mcp/servers",
+ Some(json!({"name": "echo", "transport": "stdio", "command": KWNT, "args": ["mcp-echo-server"]}))).await;
+ let (status, result) = call(&app, "POST", &format!("/api/mcp/servers/{}/test", ok_server["id"].as_str().unwrap()), None).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(result["ok"], true, "{result}");
+ assert_eq!(result["tools"].as_array().unwrap().len(), 5);
+ assert_eq!(result["server_info"]["name"], "kwnt-echo");
+
+ // A server that prints its secret and dies: the error comes back without the secret
+ let (_, bad) = call(&app, "POST", "/api/mcp/servers", Some(json!({
+ "name": "leaky", "transport": "stdio", "command": "sh",
+ "args": ["-c", "echo \"token is $LEAKY_TOKEN\" >&2; exit 1"],
+ "env": {"LEAKY_TOKEN": "tok-abcdef-123"}, "timeout_secs": 5}))).await;
+ let (_, result) = call(&app, "POST", &format!("/api/mcp/servers/{}/test", bad["id"].as_str().unwrap()), None).await;
+ assert_eq!(result["ok"], false, "{result}");
+ let text = result.to_string();
+ assert!(!text.contains("tok-abcdef-123"), "{text}");
+ assert!(result["stderr_tail"].as_str().unwrap().contains(&format!("token is {SECRET_MASK}")), "{text}");
+
+ let (status, _) = call(&app, "POST", "/api/mcp/servers/nope/test", None).await;
+ assert_eq!(status, StatusCode::NOT_FOUND);
+}