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 step 2: claude CLI agents get their MCP servers, with approvals

Lin (kwant bot)e47d8a02f5cf
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 7eef2566..0a061eca 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -94,7 +94,11 @@ Body: `{"server_ids": ["…"]}` (replaces the whole assignment; `[]` clears it).
- **Tool names** are `mcp__<server>__<tool>`.
- **CLI agents (`claude`)**: each turn kwnt writes a private config file (mode 0600) under
`<data_dir>/mcp/` with the kwant's enabled servers and passes it with
- `--mcp-config <file> --strict-mcp-config`; the file is removed after the turn.
+ `--mcp-config <file> --strict-mcp-config`; the file is removed after the turn. Secrets are
+ only in that file, never on the command line. claude's permission prompts go to kwnt
+ (`--permission-prompt-tool mcp__kwnt__approve`, served at `POST /api/mcp/permission/<token>`,
+ valid only while that turn runs), so only the kwant's own MCP tools can be approved; claude's
+ built-in tools stay denied as before.
`codex` and `grok` CLI agents do not get MCP servers yet (no way to route their tool approvals
through kwnt); kwnt explicitly disables MCP for codex.
- **API agents** (OpenAI-compatible chat endpoints, incl. Ollama): kwnt connects to the servers,
@@ -136,6 +140,10 @@ status `allowed` or `denied` and no `result`.
runtime a server needs (`node`, `python`, `uvx` …) must be installed by the user, as usual.
- Stdio servers started by kwnt get a minimal environment (`PATH`, `HOME`, `USER`, `LANG`,
`TMPDIR`) plus the server's `env`, not kwnt's own environment (which may hold API keys).
+ Stdio servers of a `claude` CLI agent are started by claude itself and inherit claude's
+ environment (and so kwnt's) plus the server's `env`.
+- CLI agents reach kwnt's permission endpoint at `http://127.0.0.1:<port>` (or the configured
+ host when it is a specific address), so the CLI must run on the same machine as kwnt.
- Registering a stdio server lets the caller run any command as the kwnt user. The kwnt API has no
authentication of its own: on a VPS keep it bound to `127.0.0.1` or behind an authenticating
reverse proxy.
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
index c48cca96..e1ca3125 100644
--- a/src/broker/mod.rs
+++ b/src/broker/mod.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::{oneshot, Mutex};
@@ -22,12 +22,15 @@ pub struct ApprovalRequest {
#[derive(Clone, Debug, Default)]
pub struct PermissionBroker {
pending: Arc<Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>>,
+ /// (kwant_id, tool_name) pairs the user chose "always allow" for, until kwnt restarts.
+ always_allowed: Arc<Mutex<HashSet<(String, String)>>>,
}
impl PermissionBroker {
pub fn new() -> Self {
Self {
pending: Arc::new(Mutex::new(HashMap::new())),
+ always_allowed: Arc::new(Mutex::new(HashSet::new())),
}
}
@@ -54,4 +57,18 @@ impl PermissionBroker {
false
}
}
+
+ /// Drops a pending ticket without a decision; its waiter sees the channel close.
+ pub async fn cancel(&self, ticket_id: &str) -> bool {
+ self.pending.lock().await.remove(ticket_id).is_some()
+ }
+
+ /// Remembers an "always allow" answer for this kwant and tool for the rest of the session.
+ pub async fn allow_for_session(&self, kwant_id: &str, tool_name: &str) {
+ self.always_allowed.lock().await.insert((kwant_id.to_string(), tool_name.to_string()));
+ }
+
+ pub async fn is_allowed_for_session(&self, kwant_id: &str, tool_name: &str) -> bool {
+ self.always_allowed.lock().await.contains(&(kwant_id.to_string(), tool_name.to_string()))
+ }
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index c5e3fc8e..1afc56a3 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -153,6 +153,8 @@ impl Driver for CliDriver {
}
}
let mut codex_out_file: Option<String> = None;
+ // Lives until the CLI exits; dropping it deletes the per-turn MCP config file.
+ let mut _mcp_config: Option<crate::mcp::cli_config::ConfigFile> = None;
let effort = input.effort_level.as_deref().unwrap_or("medium");
@@ -170,6 +172,15 @@ impl Driver for CliDriver {
cmd.env("BROWSER", "none");
cmd.env("DISPLAY", "");
+ if input.mcp.is_some() && matches!(self.tool_kind.as_str(), "codex" | "grok") {
+ let _ = event_tx
+ .send(RuntimeEvent::ThinkingDelta(format!(
+ "MCP servers are assigned, but kwnt can't offer MCP tools through the {} CLI yet; running without them.",
+ self.tool_kind
+ )))
+ .await;
+ }
+
match self.tool_kind.as_str() {
"codex" => {
let out_file = format!("/tmp/kwnt_codex_{}.txt", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos());
@@ -186,6 +197,10 @@ impl Driver for CliDriver {
.arg("never")
.arg("-c")
.arg(format!("reasoning_effort=\"{}\"", codex_effort))
+ // codex exec has no hook for kwnt's approval cards, so no MCP servers at all,
+ // including ones from the user's own config.toml
+ .arg("-c")
+ .arg("mcp_servers={}")
.arg("-o")
.arg(&out_file)
.arg(&full_prompt);
@@ -213,6 +228,30 @@ impl Driver for CliDriver {
cmd.arg("--effort").arg(claude_effort);
// Skip starting the user's personal MCP servers on every chat turn
cmd.arg("--strict-mcp-config");
+ if let Some(ctx) = &input.mcp {
+ match crate::mcp::cli_config::write_claude_config(ctx) {
+ Ok(file) => {
+ cmd.arg("--mcp-config").arg(&file.path);
+ cmd.arg("--permission-prompt-tool").arg(format!(
+ "mcp__{}__{}",
+ crate::mcp::RESERVED_SERVER_NAME,
+ crate::mcp::PERMISSION_TOOL
+ ));
+ // A tool call may wait for the user's approval; claude must not give up first
+ let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);
+ let tool_timeout_ms = (crate::mcp::APPROVAL_TIMEOUT_SECS + 30).max(slowest) * 1000;
+ cmd.env("MCP_TOOL_TIMEOUT", tool_timeout_ms.to_string());
+ cmd.env("MCP_TIMEOUT", "30000");
+ _mcp_config = Some(file);
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "could not write MCP config; running without MCP");
+ let _ = event_tx
+ .send(RuntimeEvent::ThinkingDelta("MCP tools are unavailable this turn (config file error).".into()))
+ .await;
+ }
+ }
+ }
cmd.arg("--append-system-prompt").arg(&system_prompt);
cmd.arg("-p").arg(&effective_prompt);
}
@@ -350,6 +389,7 @@ mod tests {
workspace_dir: None,
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let result = build_cli_prompt(&input);
@@ -388,6 +428,7 @@ mod tests {
workspace_dir: None,
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let result = build_cli_prompt(&input);
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index c78d94da..c6bea847 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -51,6 +51,9 @@ pub struct TurnInput {
/// Other kwants in this chat that the speaker can hand the turn to with an @mention.
#[serde(default)]
pub teammates: Vec<Teammate>,
+ /// MCP servers, approver and records for this turn; `None` when the kwant has none.
+ #[serde(skip)]
+ pub mcp: Option<crate::mcp::McpTurnContext>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/src/mcp/cli_config.rs b/src/mcp/cli_config.rs
new file mode 100644
index 00000000..aadc4269
--- /dev/null
+++ b/src/mcp/cli_config.rs
@@ -0,0 +1,64 @@
+//! Per-turn MCP config file for the claude CLI. Secrets go in the file (mode 0600, inside the
+//! data dir), never in argv, and the file is removed when the guard drops.
+
+use super::McpTurnContext;
+use serde_json::{json, Map, Value};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+/// The `--mcp-config` document: the kwant's servers plus kwnt's permission endpoint.
+pub fn claude_config(ctx: &McpTurnContext) -> Value {
+ let mut servers = Map::new();
+ for s in &ctx.servers {
+ let entry = if s.transport == "http" {
+ json!({"type": "http", "url": s.url, "headers": s.headers})
+ } else {
+ json!({"type": "stdio", "command": s.command, "args": s.args, "env": s.env})
+ };
+ servers.insert(s.name.clone(), entry);
+ }
+ if let Some(url) = &ctx.permission_url {
+ servers.insert(super::RESERVED_SERVER_NAME.to_string(), json!({"type": "http", "url": url}));
+ }
+ json!({ "mcpServers": servers })
+}
+
+/// Removes the config file when the turn ends, including when it is aborted.
+#[derive(Debug)]
+pub struct ConfigFile {
+ pub path: PathBuf,
+}
+
+impl Drop for ConfigFile {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.path);
+ }
+}
+
+fn create_private_dir(dir: &Path) -> std::io::Result<()> {
+ std::fs::create_dir_all(dir)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
+ }
+ Ok(())
+}
+
+/// Writes a fresh config file for this turn in `ctx.config_dir`.
+pub fn write_claude_config(ctx: &McpTurnContext) -> std::io::Result<ConfigFile> {
+ create_private_dir(&ctx.config_dir)?;
+ let path = ctx.config_dir.join(format!("claude-{}.json", uuid::Uuid::new_v4().simple()));
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&path)?;
+ let guard = ConfigFile { path };
+ file.write_all(serde_json::to_string_pretty(&claude_config(ctx))?.as_bytes())?;
+ file.sync_all()?;
+ Ok(guard)
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index bcda9e89..4ae793a9 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -1,6 +1,7 @@
//! 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 cli_config;
pub mod client;
pub mod echo_server;
@@ -22,6 +23,10 @@ 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;
+/// How long an MCP tool call waits for the user's approval before it is denied.
+pub const APPROVAL_TIMEOUT_SECS: u64 = 300;
+/// kwnt's permission-prompt tool for the claude CLI, called as `mcp__kwnt__approve`.
+pub const PERMISSION_TOOL: &str = "approve";
/// API representation of a server: secrets replaced by [`SECRET_MASK`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
new file mode 100644
index 00000000..d38cdcbd
--- /dev/null
+++ b/src/server/mcp_runtime.rs
@@ -0,0 +1,284 @@
+//! MCP at turn time: the broker-backed approver, per-turn context setup, and the small MCP
+//! endpoint the claude CLI calls (`--permission-prompt-tool`) so its MCP tool calls get the same
+//! approval cards as API agents.
+
+use super::AppState;
+use crate::broker::{ApprovalDecision, ApprovalRequest, PermissionBroker};
+use crate::db::models::{Kwant, NewApproval};
+use crate::db::Database;
+use crate::drivers::events::RuntimeEvent;
+use crate::mcp::{self, client::PROTOCOL_VERSION, McpTurnContext, ToolApprovalRequest, ToolApprover};
+use async_trait::async_trait;
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::sync::broadcast;
+
+/// How long a tool call waits for the user before it is denied.
+pub const APPROVAL_TIMEOUT: Duration = Duration::from_secs(mcp::APPROVAL_TIMEOUT_SECS);
+/// The tool claude calls for permission decisions: `mcp__kwnt__approve`.
+pub use crate::mcp::PERMISSION_TOOL;
+
+/// A claude CLI turn whose permission prompts kwnt answers.
+#[derive(Clone)]
+pub struct PermissionSession {
+ pub kwant_id: String,
+ pub kwant_name: String,
+ pub turn_id: String,
+ pub ctx: McpTurnContext,
+}
+
+/// Asks the user through the permission broker: stores the ticket, emits `ApprovalRequired`
+/// and waits for `/api/approvals/:id/resolve`, a timeout, or the turn being dropped.
+pub struct BrokerApprover {
+ pub db: Database,
+ pub broker: PermissionBroker,
+ pub events: broadcast::Sender<RuntimeEvent>,
+ pub timeout: Duration,
+}
+
+/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.
+struct TicketGuard {
+ id: Option<String>,
+ broker: PermissionBroker,
+ db: Database,
+}
+
+impl Drop for TicketGuard {
+ fn drop(&mut self) {
+ let (Some(id), Ok(handle)) = (self.id.take(), tokio::runtime::Handle::try_current()) else {
+ return;
+ };
+ let (broker, db) = (self.broker.clone(), self.db.clone());
+ handle.spawn(async move {
+ if broker.cancel(&id).await {
+ let _ = db.update_approval_status(&id, "cancelled").await;
+ }
+ });
+ }
+}
+
+#[async_trait]
+impl ToolApprover for BrokerApprover {
+ async fn approve(&self, req: ToolApprovalRequest) -> bool {
+ if self.broker.is_allowed_for_session(&req.kwant_id, &req.tool_name).await {
+ return true;
+ }
+ let details = json!({
+ "source": "mcp",
+ "server": req.server,
+ "tool": req.tool,
+ "arguments": req.arguments,
+ "kwant_id": req.kwant_id,
+ "kwant_name": req.kwant_name,
+ });
+ let ticket = match self
+ .db
+ .save_approval(&NewApproval {
+ turn_id: req.turn_id.clone(),
+ kwant_id: req.kwant_id.clone(),
+ tool_name: req.tool_name.clone(),
+ parameters: details.clone(),
+ })
+ .await
+ {
+ Ok(a) => a.id,
+ Err(e) => {
+ tracing::warn!(error = %e, "could not store MCP approval ticket; denying");
+ return false;
+ }
+ };
+ let rx = self
+ .broker
+ .request_approval(ApprovalRequest {
+ id: ticket.clone(),
+ kwant_id: req.kwant_id.clone(),
+ tool_name: req.tool_name.clone(),
+ details: details.clone(),
+ })
+ .await;
+ let mut guard = TicketGuard { id: Some(ticket.clone()), broker: self.broker.clone(), db: self.db.clone() };
+ let _ = self.events.send(RuntimeEvent::ApprovalRequired {
+ id: ticket.clone(),
+ tool_name: req.tool_name.clone(),
+ details,
+ });
+
+ let decision = tokio::time::timeout(self.timeout, rx).await;
+ guard.id = None;
+ match decision {
+ Ok(Ok(ApprovalDecision::AllowOnce)) => true,
+ Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {
+ self.broker.allow_for_session(&req.kwant_id, &req.tool_name).await;
+ true
+ }
+ Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => false,
+ Err(_) => {
+ self.broker.cancel(&ticket).await;
+ let _ = self.db.update_approval_status(&ticket, "expired").await;
+ false
+ }
+ }
+ }
+}
+
+fn max_tool_iterations(setting: Option<String>) -> usize {
+ setting
+ .or_else(|| std::env::var("KWNT_MCP_MAX_TOOL_ITERATIONS").ok())
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .unwrap_or(mcp::DEFAULT_MAX_TOOL_ITERATIONS)
+ .clamp(1, 50)
+}
+
+/// Address agent CLIs on this host use to reach kwnt.
+fn local_base_url(state: &AppState) -> String {
+ let host = match state.config.host.as_str() {
+ "0.0.0.0" | "::" | "[::]" | "" | "localhost" => "127.0.0.1".to_string(),
+ h if h.contains(':') && !h.starts_with('[') => format!("[{h}]"),
+ h => h.to_string(),
+ };
+ format!("http://{host}:{}", state.config.port)
+}
+
+/// Builds the turn's MCP context when the kwant has enabled servers, and registers the
+/// permission session claude will call. Returns `None` (no behaviour change) otherwise.
+/// Pair with [`finish_turn`].
+pub async fn prepare_turn(state: &AppState, kwant: &Kwant) -> Option<(McpTurnContext, String)> {
+ let servers = match state.db.list_active_mcp_servers_for_kwant(&kwant.id).await {
+ Ok(s) if !s.is_empty() => s,
+ Ok(_) => return None,
+ Err(e) => {
+ tracing::warn!(error = %e, "could not load MCP servers for kwant");
+ return None;
+ }
+ };
+ let token = uuid::Uuid::new_v4().simple().to_string();
+ let setting = state.db.get_setting("mcp_max_tool_iterations").await.ok().flatten();
+ let ctx = McpTurnContext {
+ servers,
+ approver: Arc::new(BrokerApprover {
+ db: state.db.clone(),
+ broker: state.broker.clone(),
+ events: state.event_sender.clone(),
+ timeout: APPROVAL_TIMEOUT,
+ }),
+ config_dir: state.config.data_dir.join("mcp"),
+ permission_url: Some(format!("{}/api/mcp/permission/{token}", local_base_url(state))),
+ max_tool_iterations: max_tool_iterations(setting),
+ records: Default::default(),
+ };
+ let session = PermissionSession {
+ kwant_id: kwant.id.clone(),
+ kwant_name: kwant.name.clone(),
+ turn_id: uuid::Uuid::new_v4().to_string(),
+ ctx: ctx.clone(),
+ };
+ state.mcp_sessions.lock().await.insert(token.clone(), session);
+ Some((ctx, token))
+}
+
+pub async fn finish_turn(state: &AppState, token: &str) {
+ state.mcp_sessions.lock().await.remove(token);
+}
+
+fn rpc_result(id: Value, result: Value) -> Response {
+ Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response()
+}
+
+fn rpc_error(id: Value, code: i64, message: &str) -> Response {
+ Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})).into_response()
+}
+
+/// Answers one claude permission prompt. Only MCP tools from the kwant's own servers can be
+/// approved here; anything else is denied, as it would be in `-p` mode without this handler.
+async fn decide(session: &PermissionSession, args: &Value) -> Value {
+ let tool_name = args["tool_name"].as_str().unwrap_or("");
+ let input = args.get("input").cloned().unwrap_or_else(|| json!({}));
+ let tool_use_id = args["tool_use_id"].as_str().unwrap_or("").to_string();
+
+ let target = mcp::split_tool_name(tool_name)
+ .filter(|(server, _)| session.ctx.servers.iter().any(|s| s.name == *server));
+ let Some((server, tool)) = target else {
+ return json!({"behavior": "deny", "message": format!("{tool_name} is not available to this kwant.")});
+ };
+ let allowed = session
+ .ctx
+ .approver
+ .approve(ToolApprovalRequest {
+ kwant_id: session.kwant_id.clone(),
+ kwant_name: session.kwant_name.clone(),
+ turn_id: session.turn_id.clone(),
+ tool_name: tool_name.to_string(),
+ server: server.to_string(),
+ tool: tool.to_string(),
+ arguments: input.clone(),
+ })
+ .await;
+ session.ctx.record(json!({
+ "id": tool_use_id,
+ "name": tool_name,
+ "server": server,
+ "tool": tool,
+ "arguments": input,
+ "status": if allowed { "allowed" } else { "denied" },
+ }));
+ if allowed {
+ json!({"behavior": "allow", "updatedInput": input})
+ } else {
+ json!({"behavior": "deny", "message": "The user denied this tool call."})
+ }
+}
+
+/// `POST /api/mcp/permission/:token`: a minimal streamable-HTTP MCP server (JSON responses).
+pub async fn permission_endpoint(
+ State(state): State<AppState>,
+ Path(token): Path<String>,
+ Json(msg): Json<Value>,
+) -> Response {
+ let session = state.mcp_sessions.lock().await.get(&token).cloned();
+ let Some(session) = session else {
+ return StatusCode::NOT_FOUND.into_response();
+ };
+ let Some(id) = msg.get("id").cloned() else {
+ return StatusCode::ACCEPTED.into_response(); // notification
+ };
+ match msg["method"].as_str().unwrap_or("") {
+ "initialize" => rpc_result(
+ id,
+ json!({
+ "protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or(PROTOCOL_VERSION),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": mcp::RESERVED_SERVER_NAME, "version": env!("CARGO_PKG_VERSION")},
+ }),
+ ),
+ "ping" => rpc_result(id, json!({})),
+ "tools/list" => rpc_result(
+ id,
+ json!({"tools": [{
+ "name": PERMISSION_TOOL,
+ "description": "kwnt's permission prompt handler. Not for direct use.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "tool_name": {"type": "string"},
+ "input": {"type": "object"},
+ "tool_use_id": {"type": "string"},
+ },
+ "required": ["tool_name", "input"],
+ },
+ }]}),
+ ),
+ "tools/call" if msg["params"]["name"] == PERMISSION_TOOL => {
+ let decision = decide(&session, &msg["params"]["arguments"]).await;
+ rpc_result(id, json!({"content": [{"type": "text", "text": decision.to_string()}]}))
+ }
+ "tools/call" => rpc_error(id, -32602, "unknown tool"),
+ _ => rpc_error(id, -32601, "method not found"),
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 5cf6efbf..da3ac505 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -3,6 +3,7 @@ pub mod routes;
pub mod sse;
pub mod browser_stream;
pub mod mcp_routes;
+pub mod mcp_runtime;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -33,6 +34,8 @@ pub struct AppState {
pub sandbox_manager: Arc<SandboxManager>,
pub browser_controllers: Arc<Mutex<HashMap<String, BrowserController>>>,
pub browser_service: Arc<crate::sandbox::service::BrowserService>,
+ /// Live claude CLI turns whose MCP permission prompts kwnt answers, by URL token.
+ pub mcp_sessions: Arc<Mutex<HashMap<String, mcp_runtime::PermissionSession>>>,
}
impl AppState {
@@ -58,6 +61,7 @@ impl AppState {
sandbox_manager,
browser_controllers,
browser_service,
+ mcp_sessions: Arc::new(Mutex::new(HashMap::new())),
}
}
@@ -106,6 +110,7 @@ pub fn create_router(state: AppState) -> Router {
)
.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/mcp/permission/:token", post(mcp_runtime::permission_endpoint))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(cors)
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 2b6ada6a..b424ed54 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -668,6 +668,8 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,
}
let driver = resolve_driver_for_model(&target_model, configured_key, endpoint);
+ let mcp_turn = super::mcp_runtime::prepare_turn(&state, &target_kwant).await;
+ let mcp_ctx = mcp_turn.as_ref().map(|(ctx, _)| ctx.clone());
let turn_input = TurnInput {
browser_api_url: Some(format!("http://127.0.0.1:{}/api/sandbox/{}", state.config.port, sandbox_target)),
thread_id: context_id,
@@ -685,6 +687,7 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,
.filter(|k| k.id != target_kwant.id)
.map(|k| crate::drivers::Teammate { name: k.name.clone(), title: k.title.clone() })
.collect(),
+ mcp: mcp_ctx.clone(),
};
let (driver_tx, mut driver_rx) = mpsc::channel(32);
@@ -711,9 +714,15 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,
}
}
+ let driver_result = if cancelled { None } else { Some(driver_task.await) };
+ if let Some((_, token)) = &mcp_turn {
+ super::mcp_runtime::finish_turn(&state, token).await;
+ }
+ let mcp_records = mcp_ctx.map(|c| c.take_records()).filter(|r| !r.is_empty());
+
if cancelled {
let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));
- } else if let Ok(Ok(output)) = driver_task.await {
+ } else if let Some(Ok(Ok(output))) = driver_result {
// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VM
if let Some(bot_url) = extract_url_from_text(&output.text) {
if let Some(ctrl) = get_or_create_browser_controller(&state, &sandbox_target).await {
@@ -758,7 +767,7 @@ async fn run_kwant_turn(scope: &TurnScope, target_kwant: &Kwant, prompt: String,
sender_id: target_kwant.name.clone(),
text,
reasoning_content,
- tool_calls: None,
+ tool_calls: mcp_records.map(serde_json::Value::Array),
tokens_used: output.tokens_used as i64,
};
let _ = db.insert_message(&asst_msg).await;
diff --git a/tests/driver_test.rs b/tests/driver_test.rs
index 8c4b4e58..510db659 100644
--- a/tests/driver_test.rs
+++ b/tests/driver_test.rs
@@ -89,6 +89,7 @@ async fn test_mock_driver_streaming() {
workspace_dir: None,
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let handle = tokio::spawn(async move {
@@ -147,6 +148,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
workspace_dir: None,
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let solo_prompt = input_solo.format_system_prompt();
@@ -195,6 +197,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
workspace_dir: None,
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let team_prompt = input_team.format_system_prompt();
@@ -222,6 +225,7 @@ fn test_turn_input_format_system_prompt_with_and_without_team_context() {
workspace_dir: Some(std::path::PathBuf::from("/Users/dev/app")),
sandbox_id: None,
teammates: vec![],
+ mcp: None,
};
let ws_prompt = input_workspace.format_system_prompt();
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
new file mode 100644
index 00000000..259f4d35
--- /dev/null
+++ b/tests/mcp_runtime_test.rs
@@ -0,0 +1,364 @@
+//! Turn-time MCP: broker approvals, the claude permission endpoint and the claude config file.
+
+use kwnt::{
+ broker::{ApprovalDecision, PermissionBroker},
+ config::Config,
+ db::{models::McpServer, Database},
+ db::models::Kwant,
+ drivers::{events::RuntimeEvent, CliDriver, Driver, TurnInput},
+ mcp::{cli_config, FixedApprover, McpClient, McpTurnContext, ToolApprovalRequest, ToolApprover},
+ router::LayaRouter,
+ server::{create_router, mcp_runtime::{BrokerApprover, PermissionSession}, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::sync::Arc;
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+
+fn server(name: &str) -> McpServer {
+ McpServer {
+ id: format!("id-{name}"),
+ name: name.into(),
+ transport: "stdio".into(),
+ command: Some("/usr/bin/true".into()),
+ args: vec!["--flag".into()],
+ url: None,
+ env: BTreeMap::from([("API_TOKEN".to_string(), "sk-very-secret".to_string())]),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs: 30,
+ created_at: None,
+ }
+}
+
+fn ctx(dir: &std::path::Path, approver: Arc<dyn ToolApprover>) -> McpTurnContext {
+ let mut http = server("remote");
+ http.transport = "http".into();
+ http.command = None;
+ http.args = vec![];
+ http.env = BTreeMap::new();
+ http.url = Some("https://mcp.example.test/mcp".into());
+ http.headers = BTreeMap::from([("Authorization".to_string(), "Bearer hdr-secret".to_string())]);
+ McpTurnContext {
+ servers: vec![server("echo"), http],
+ approver,
+ config_dir: dir.join("mcp"),
+ permission_url: Some("http://127.0.0.1:1/api/mcp/permission/tok".into()),
+ max_tool_iterations: 8,
+ records: Default::default(),
+ }
+}
+
+async fn state() -> (AppState, 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,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (state, tmp)
+}
+
+fn request(tool: &str) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: "k1".into(),
+ kwant_name: "Ada".into(),
+ turn_id: "t1".into(),
+ tool_name: format!("mcp__echo__{tool}"),
+ server: "echo".into(),
+ tool: tool.into(),
+ arguments: json!({"text": "hi"}),
+ }
+}
+
+/// Starts an approval and returns (join handle, ticket id from the ApprovalRequired event).
+async fn ask(state: &AppState, approver: Arc<BrokerApprover>, tool: &str) -> (tokio::task::JoinHandle<bool>, String) {
+ let mut events = state.event_sender.subscribe();
+ let req = request(tool);
+ let handle = tokio::spawn(async move { approver.approve(req).await });
+ let ticket = loop {
+ match tokio::time::timeout(Duration::from_secs(5), events.recv()).await.unwrap().unwrap() {
+ RuntimeEvent::ApprovalRequired { id, tool_name, details } => {
+ assert_eq!(tool_name, format!("mcp__echo__{tool}"));
+ assert_eq!(details["source"], "mcp");
+ assert_eq!(details["server"], "echo");
+ assert_eq!(details["arguments"]["text"], "hi");
+ break id;
+ }
+ _ => continue,
+ }
+ };
+ (handle, ticket)
+}
+
+fn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {
+ Arc::new(BrokerApprover {
+ db: state.db.clone(),
+ broker: state.broker.clone(),
+ events: state.event_sender.clone(),
+ timeout,
+ })
+}
+
+#[tokio::test]
+async fn broker_approver_follows_user_decisions() {
+ let (state, _tmp) = state().await;
+ let a = approver(&state, Duration::from_secs(10));
+
+ let (h, ticket) = ask(&state, a.clone(), "echo").await;
+ assert!(state.broker.resolve(&ticket, ApprovalDecision::Deny).await);
+ assert!(!h.await.unwrap(), "denied by broker");
+
+ let (h, ticket) = ask(&state, a.clone(), "echo").await;
+ assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "pending");
+ state.broker.resolve(&ticket, ApprovalDecision::AllowOnce).await;
+ assert!(h.await.unwrap());
+
+ // "Always allow" sticks for this kwant and tool, without another card
+ let (h, ticket) = ask(&state, a.clone(), "add").await;
+ state.broker.resolve(&ticket, ApprovalDecision::AlwaysAllowSession).await;
+ assert!(h.await.unwrap());
+ let mut req = request("add");
+ req.arguments = json!({"a": 1, "b": 2});
+ assert!(tokio::time::timeout(Duration::from_secs(1), a.approve(req)).await.unwrap());
+ let mut other_kwant = request("add");
+ other_kwant.kwant_id = "k2".into();
+ assert!(tokio::time::timeout(Duration::from_millis(300), a.approve(other_kwant)).await.is_err(), "k2 must still ask");
+}
+
+#[tokio::test]
+async fn unanswered_approval_expires_as_denied() {
+ let (state, _tmp) = state().await;
+ let (h, ticket) = ask(&state, approver(&state, Duration::from_millis(300)), "echo").await;
+ assert!(!h.await.unwrap());
+ assert!(!state.broker.is_pending(&ticket).await);
+ assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "expired");
+}
+
+#[tokio::test]
+async fn aborted_turn_withdraws_its_ticket() {
+ let (state, _tmp) = state().await;
+ let (h, ticket) = ask(&state, approver(&state, Duration::from_secs(30)), "echo").await;
+ h.abort();
+ let _ = h.await;
+ for _ in 0..50 {
+ if !state.broker.is_pending(&ticket).await {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ assert!(!state.broker.is_pending(&ticket).await);
+}
+
+#[tokio::test]
+async fn claude_config_file_is_private_and_removed() {
+ let tmp = tempdir().unwrap();
+ let c = ctx(tmp.path(), Arc::new(FixedApprover(true)));
+ let path;
+ {
+ let file = cli_config::write_claude_config(&c).unwrap();
+ path = file.path.clone();
+ assert!(path.starts_with(tmp.path().join("mcp")));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
+ assert_eq!(std::fs::metadata(tmp.path().join("mcp")).unwrap().permissions().mode() & 0o777, 0o700);
+ }
+ let doc: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ let servers = &doc["mcpServers"];
+ assert_eq!(servers["echo"]["type"], "stdio");
+ assert_eq!(servers["echo"]["command"], "/usr/bin/true");
+ assert_eq!(servers["echo"]["env"]["API_TOKEN"], "sk-very-secret");
+ assert_eq!(servers["remote"]["type"], "http");
+ assert_eq!(servers["remote"]["headers"]["Authorization"], "Bearer hdr-secret");
+ assert_eq!(servers["kwnt"]["url"], "http://127.0.0.1:1/api/mcp/permission/tok");
+ // A second turn gets its own file
+ let second = cli_config::write_claude_config(&c).unwrap();
+ assert_ne!(second.path, path);
+ }
+ assert!(!path.exists(), "config file must be removed after the turn");
+}
+
+async fn serve(state: AppState) -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, create_router(state)).await.unwrap() });
+ format!("http://{addr}")
+}
+
+fn http_server(url: String) -> McpServer {
+ McpServer {
+ id: "kwnt".into(),
+ name: "kwnt".into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: Some(url),
+ env: BTreeMap::new(),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs: 10,
+ created_at: None,
+ }
+}
+
+#[tokio::test]
+async fn permission_endpoint_answers_claude_prompts_over_http() {
+ let (state, tmp) = state().await;
+ let base = serve(state.clone()).await;
+
+ for (token, allow) in [("allow-tok", true), ("deny-tok", false)] {
+ let c = ctx(tmp.path(), Arc::new(FixedApprover(allow)));
+ state.mcp_sessions.lock().await.insert(
+ token.into(),
+ PermissionSession { kwant_id: "k1".into(), kwant_name: "Ada".into(), turn_id: "t1".into(), ctx: c },
+ );
+ }
+
+ // kwnt's own HTTP MCP client doubles as the streamable-HTTP test client
+ let mut client = McpClient::connect(&http_server(format!("{base}/api/mcp/permission/allow-tok")), None).await.unwrap();
+ assert_eq!(client.server_info["name"], "kwnt");
+ let tools = client.list_tools().await.unwrap();
+ assert_eq!(tools.len(), 1);
+ assert_eq!(tools[0].name, "approve");
+
+ let ask = |tool: &str| json!({"tool_name": tool, "input": {"text": "hi"}, "tool_use_id": "tu_1"});
+ let allowed: Value = serde_json::from_str(&client.call_tool("approve", ask("mcp__echo__echo")).await.unwrap().text).unwrap();
+ assert_eq!(allowed, json!({"behavior": "allow", "updatedInput": {"text": "hi"}}));
+ // Built-in tools and servers the kwant doesn't have are refused without asking
+ for tool in ["Bash", "mcp__other__echo", "mcp__kwnt__approve"] {
+ let d: Value = serde_json::from_str(&client.call_tool("approve", ask(tool)).await.unwrap().text).unwrap();
+ assert_eq!(d["behavior"], "deny", "{tool}");
+ }
+ assert!(client.call_tool("nope", json!({})).await.is_err());
+ client.shutdown().await;
+
+ let mut denied = McpClient::connect(&http_server(format!("{base}/api/mcp/permission/deny-tok")), None).await.unwrap();
+ let d: Value = serde_json::from_str(&denied.call_tool("approve", ask("mcp__echo__add")).await.unwrap().text).unwrap();
+ assert_eq!(d["behavior"], "deny");
+ denied.shutdown().await;
+
+ let sessions = state.mcp_sessions.lock().await;
+ let allow_records = sessions["allow-tok"].ctx.take_records();
+ assert_eq!(allow_records.len(), 1, "only real approval decisions are recorded");
+ assert_eq!(allow_records[0]["name"], "mcp__echo__echo");
+ assert_eq!(allow_records[0]["status"], "allowed");
+ assert_eq!(allow_records[0]["id"], "tu_1");
+ assert_eq!(sessions["deny-tok"].ctx.take_records()[0]["status"], "denied");
+ drop(sessions);
+
+ // Unknown or finished turns are not reachable
+ assert!(McpClient::connect(&http_server(format!("{base}/api/mcp/permission/gone")), None).await.is_err());
+}
+
+fn turn(mcp: Option<McpTurnContext>) -> TurnInput {
+ TurnInput {
+ browser_api_url: None,
+ thread_id: "t1".into(),
+ kwant: Kwant {
+ id: "k1".into(),
+ name: "Ada".into(),
+ title: "Lead".into(),
+ persona_prompt: "p".into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "cli".into(),
+ preferred_model: "claude".into(),
+ temperature: 0.7,
+ max_tokens: 1000,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ },
+ prompt: "hi".into(),
+ history: vec![],
+ model_override: None,
+ effort_level: Some("low".into()),
+ team_context: None,
+ workspace_dir: None,
+ sandbox_id: None,
+ teammates: vec![],
+ mcp,
+ }
+}
+
+/// Runs the CLI driver against a fake CLI that prints its argv, the config file's mode and
+/// MCP_TOOL_TIMEOUT, so the real invocation can be checked without the real CLI.
+async fn fake_cli_run(kind: &str, mcp: Option<McpTurnContext>) -> String {
+ let dir = tempdir().unwrap();
+ let script = dir.path().join("fake-cli");
+ std::fs::write(
+ &script,
+ "#!/bin/sh\necho \"ARGS: $*\"\nwhile [ $# -gt 0 ]; do\n if [ \"$1\" = --mcp-config ]; then echo \"MODE: $(stat -c %a \"$2\")\"; fi\n shift\ndone\necho \"TOOL_TIMEOUT: $MCP_TOOL_TIMEOUT\"\n",
+ )
+ .unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let driver = CliDriver::new(Some(script.to_string_lossy().into_owned()), Some(kind.into()));
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });
+ let out = driver.stream_turn(turn(mcp), tx).await.unwrap();
+ drain.await.unwrap();
+ out.text
+}
+
+#[cfg(target_os = "linux")]
+#[tokio::test]
+async fn claude_cli_gets_mcp_config_without_secrets_in_argv() {
+ let tmp = tempdir().unwrap();
+ let c = ctx(tmp.path(), Arc::new(FixedApprover(true)));
+ let out = fake_cli_run("claude", Some(c)).await;
+ assert!(out.contains("--strict-mcp-config"), "{out}");
+ assert!(out.contains(&format!("--mcp-config {}", tmp.path().join("mcp").display())), "{out}");
+ assert!(out.contains("--permission-prompt-tool mcp__kwnt__approve"), "{out}");
+ assert!(out.contains("MODE: 600"), "{out}");
+ assert!(out.contains("TOOL_TIMEOUT: 330000"), "{out}");
+ assert!(!out.contains("sk-very-secret") && !out.contains("hdr-secret"), "secrets leaked into argv: {out}");
+ assert_eq!(std::fs::read_dir(tmp.path().join("mcp")).unwrap().count(), 0, "config file left behind");
+
+ // Without servers the invocation is unchanged
+ let plain = fake_cli_run("claude", None).await;
+ assert!(plain.contains("--strict-mcp-config") && !plain.contains("--mcp-config") && !plain.contains("permission-prompt"), "{plain}");
+}
+
+#[cfg(target_os = "linux")]
+#[tokio::test]
+async fn codex_cli_runs_with_mcp_disabled() {
+ let tmp = tempdir().unwrap();
+ // codex prints its answer to an -o file, so this fake logs its argv to a file instead
+ let dir = tempdir().unwrap();
+ let script = dir.path().join("codex");
+ let log = dir.path().join("argv");
+ std::fs::write(&script, format!("#!/bin/sh\necho \"$*\" > {}\n", log.display())).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ let driver = CliDriver::new(Some(script.to_string_lossy().into_owned()), Some("codex".into()));
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let drain = tokio::spawn(async move {
+ let mut notes = Vec::new();
+ while let Some(ev) = rx.recv().await {
+ if let RuntimeEvent::ThinkingDelta(t) = ev {
+ notes.push(t);
+ }
+ }
+ notes
+ });
+ driver.stream_turn(turn(Some(ctx(tmp.path(), Arc::new(FixedApprover(true))))), tx).await.unwrap();
+ let notes = drain.await.unwrap();
+ let argv = std::fs::read_to_string(&log).unwrap();
+ assert!(argv.contains("-c mcp_servers={}"), "{argv}");
+ assert!(notes.iter().any(|n| n.contains("can't offer MCP tools through the codex CLI")), "{notes:?}");
+}