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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Codex MCP: hide the user's own codex servers, end calls with the turn
Lin (kwant bot)7d0fee68274c
diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex c7529d04..39d3329e 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -158,12 +158,19 @@ Body: `{"server_ids": ["…"]}` (replaces the whole assignment; `[]` clears it).- **CLI agents (`codex`)**: codex gets exactly one MCP server, kwnt's per-turn gateway(`POST /api/mcp/gateway`), via`-c mcp_servers={kwnt={url=…,bearer_token_env_var="KWNT_MCP_GATEWAY_TOKEN",default_tools_approval_mode="approve",…}}`.- The user's own `config.toml` servers are never loaded. The turn's token is passed in the- `KWNT_MCP_GATEWAY_TOKEN` env variable and sent as `Authorization: Bearer`, never on the command- line; other tokens and finished turns get `401`. The gateway connects to the kwant's servers+ A `-c` table is merged into codex's config rather than replacing it, so kwnt first asks codex+ which servers it would load for the turn (`codex mcp list --json`, run in the turn's working+ directory: user config, profile, trusted-project `.codex/config.toml`, system config) and adds+ `"<name>"={enabled=false}` for each one into the same table, so they are neither offered nor+ started. If that listing fails, kwnt doesn't run codex for the turn. The turn's token is passed+ in the `KWNT_MCP_GATEWAY_TOKEN` env variable and sent as `Authorization: Bearer`, never on the+ command line, and blanked for codex's own shell commands+ (`-c shell_environment_policy.set.KWNT_MCP_GATEWAY_TOKEN=""`); other tokens and finished turns+ get `401`. The gateway connects to the kwant's serverson first use, lists their tools as `<server>__<tool>` (codex shows them under `mcp__kwnt`),and asks for approval (below) before forwarding each call, so codex's own approval is turned- off for it. Without servers codex runs with `-c mcp_servers={}` as before.+ off for it. Without servers (or for a kwant that opted out) codex gets only the+ `enabled=false` entries: `-c mcp_servers={}` when the user has no servers of their own.`grok` CLI agents do not get MCP servers yet: its config overlay (`GROK_CONFIG_PATH`) cannotadd `mcp_servers`, and it has no per-run MCP flag.- **API agents** (OpenAI-compatible chat endpoints, incl. Ollama): kwnt connects to the servers,@@ -181,7 +188,11 @@ Every MCP tool call needs approval through the permission broker, for both agent2. The UI resolves it with the existing `POST /api/approvals/:id/resolve``{"decision": "allow_once" | "always_allow" | "deny"}`.`always_allow` allows that tool for that kwant until kwnt restarts.-3. Unanswered tickets are denied after 300 s, or when the turn is cancelled.+3. Unanswered tickets are denied after 300 s, or when the turn ends or is cancelled; kwnt then+ emits `{"type":"ApprovalWithdrawn","data":{"id":"<ticket>"}}` so the UI can drop the card.+ Resolving a withdrawn (or unknown) ticket returns `409` and changes nothing: its tool never+ runs, and the ticket keeps its `cancelled` or `expired` status. A call the turn ended under is+ recorded with status `cancelled`.API agents also emit `ToolCallPending {id, name, args}` before running a call and`ToolCallCompleted {id, result: {status, content}}` after it (`content` cut to 4000 characters).diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 4379cc96..b90c2965 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -213,6 +213,9 @@ export const App: React.FC = () => {});playSfx('alert');break;+ case 'ApprovalWithdrawn':+ setPendingApproval((current) => (current?.id === event.data.id ? null : current));+ break;case 'discussion_started':case 'DiscussionStarted': {discussionInProgressRef.current = true;diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 5d3ba3c5..7b34b998 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -2,7 +2,7 @@ use super::{events::RuntimeEvent, Driver, DriverError, TurnInput, TurnOutput};use async_trait::async_trait;use std::path::Path;use std::process::Stdio;-use std::time::Instant;+use std::time::{Duration, Instant};use tokio::io::AsyncReadExt;use tokio::process::Command;use tokio::sync::mpsc;@@ -74,26 +74,64 @@ fn toml_string(value: &str) -> String {serde_json::Value::String(value.to_string()).to_string()}-/// The `mcp_servers` override for `codex exec`: only kwnt's gateway, or nothing. The gateway-/// asks the user before every call, so codex's own approval is turned off for it; its token is-/// read from an env variable so it never appears in argv.-pub fn codex_mcp_servers(ctx: Option<&crate::mcp::McpTurnContext>) -> String {- let Some((ctx, gateway)) = ctx.and_then(|c| c.gateway.as_ref().map(|g| (c, g))) else {- return "mcp_servers={}".into();+/// The `mcp_servers` override for `codex exec`: kwnt's gateway (when the kwant has servers)+/// and `enabled=false` for every server codex would load from the user's own config. A `-c`+/// table is merged into codex's config, not swapped in, so the user's servers must be switched+/// off by name; the names go inside the value because codex's `-c` key path can't quote. The+/// gateway asks the user before every call, so codex's own approval is turned off for it; its+/// token is read from an env variable so it never appears in argv.+pub fn codex_mcp_servers(ctx: Option<&crate::mcp::McpTurnContext>, user_servers: &[String]) -> String {+ let mut entries = Vec::new();+ if let Some((ctx, gateway)) = ctx.and_then(|c| c.gateway.as_ref().map(|g| (c, g))) {+ let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);+ // The gateway connects to every server on codex's first tools/list+ let startup_secs = (slowest + 15).max(30);+ // A call may wait for the user's approval; codex must not give up first+ let tool_secs = (crate::mcp::APPROVAL_TIMEOUT_SECS + 30).max(slowest);+ entries.push(format!(+ "{}={{url={},bearer_token_env_var={},default_tools_approval_mode=\"approve\",startup_timeout_sec={},tool_timeout_sec={}}}",+ crate::mcp::RESERVED_SERVER_NAME,+ toml_string(&gateway.url),+ toml_string(crate::mcp::GATEWAY_TOKEN_ENV),+ startup_secs,+ tool_secs,+ ));+ }+ for name in user_servers {+ if name != crate::mcp::RESERVED_SERVER_NAME {+ entries.push(format!("{}={{enabled=false}}", toml_string(name)));+ }+ }+ format!("mcp_servers={{{}}}", entries.join(","))+}++/// How long `codex mcp list` may take before the turn is refused.+const CODEX_MCP_LIST_TIMEOUT: Duration = Duration::from_secs(15);++/// Names of the MCP servers codex would load for this turn, as codex itself resolves them:+/// `$CODEX_HOME`/`~/.codex` config, its active profile, a trusted project's `.codex/config.toml`+/// for `cwd`, and system config. The listing holds server env values, so it is never logged.+pub async fn codex_user_mcp_servers(bin: &str, cwd: Option<&Path>) -> Result<Vec<String>, String> {+ let mut cmd = Command::new(bin);+ cmd.args(["mcp", "list", "--json"]);+ if let Some(dir) = cwd.filter(|d| d.exists()) {+ cmd.current_dir(dir);+ }+ cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true);+ let output = match tokio::time::timeout(CODEX_MCP_LIST_TIMEOUT, cmd.output()).await {+ Ok(Ok(o)) => o,+ Ok(Err(e)) => return Err(format!("could not run `codex mcp list`: {e}")),+ Err(_) => return Err("`codex mcp list` timed out".into()),};- let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);- // The gateway connects to every server on codex's first tools/list- let startup_secs = (slowest + 15).max(30);- // A call may wait for the user's approval; codex must not give up first- let tool_secs = (crate::mcp::APPROVAL_TIMEOUT_SECS + 30).max(slowest);- format!(- "mcp_servers={{{}={{url={},bearer_token_env_var={},default_tools_approval_mode=\"approve\",startup_timeout_sec={},tool_timeout_sec={}}}}}",- crate::mcp::RESERVED_SERVER_NAME,- toml_string(&gateway.url),- toml_string(crate::mcp::GATEWAY_TOKEN_ENV),- startup_secs,- tool_secs,- )+ if !output.status.success() {+ return Err(format!("`codex mcp list` failed ({})", output.status));+ }+ let listed: Vec<serde_json::Value> =+ serde_json::from_slice(&output.stdout).map_err(|_| "`codex mcp list --json` returned unexpected output".to_string())?;+ listed+ .iter()+ .map(|s| s["name"].as_str().map(str::to_string).ok_or_else(|| "`codex mcp list --json` entry has no name".to_string()))+ .collect()}pub fn build_cli_prompt(input: &TurnInput) -> String {@@ -216,6 +254,23 @@ impl Driver for CliDriver {_ => "medium",};let full_prompt = format!("[System Context: {}]\n\n{}", system_prompt, effective_prompt);+ // Fail closed: without the names, the user's own servers would run with no+ // approval card (and despite a per-kwant opt-out).+ let user_servers = match codex_user_mcp_servers(&bin_path, input.workspace_dir.as_deref()).await {+ Ok(names) => names,+ Err(e) => {+ tracing::warn!(error = %e, "could not list codex's own MCP servers; not running codex");+ let msg = format!(+ "⚠️ [{}] kwnt couldn't check which MCP servers your codex config would start ({e}), so it didn't run codex. Check that `codex mcp list` works.",+ input.kwant.name+ );+ let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;+ let _ = event_tx+ .send(RuntimeEvent::TurnComplete { tokens: 0, duration_ms: start.elapsed().as_millis() as u64 })+ .await;+ return Ok(TurnOutput { text: msg, reasoning: None, tokens_used: 0 });+ }+ };cmd.arg("exec").arg("--ephemeral").arg("--skip-git-repo-check")@@ -223,12 +278,15 @@ impl Driver for CliDriver {.arg("never").arg("-c").arg(format!("reasoning_effort=\"{}\"", codex_effort))- // Never the user's own config.toml servers: codex exec has no hook for kwnt's+ // Never the user's own codex servers: codex exec has no hook for kwnt's// approval cards. The kwant's servers come only through kwnt's gateway..arg("-c")- .arg(codex_mcp_servers(input.mcp.as_ref()));+ .arg(codex_mcp_servers(input.mcp.as_ref(), &user_servers));if let Some(gateway) = input.mcp.as_ref().and_then(|c| c.gateway.as_ref()) {cmd.env(crate::mcp::GATEWAY_TOKEN_ENV, &gateway.token);+ // codex's default shell env policy passes the token on to the model's shell+ // commands; blank it there (a `set` entry merges, keeping the user's policy)+ cmd.arg("-c").arg(format!("shell_environment_policy.set.{}=\"\"", crate::mcp::GATEWAY_TOKEN_ENV));}cmd.arg("-o").arg(&out_file)@@ -286,16 +344,19 @@ impl Driver for CliDriver {}}- cmd.stdout(Stdio::piped());- cmd.stderr(Stdio::piped());+ // codex's reply comes from its -o file; an unread pipe could fill up and stall the CLI+ cmd.stdin(Stdio::null());+ cmd.stdout(if codex_out_file.is_some() { Stdio::null() } else { Stdio::piped() });+ cmd.stderr(Stdio::null());+ // A cancelled turn aborts this task; the CLI must not outlive it+ cmd.kill_on_drop(true);match cmd.spawn() {Ok(mut child) => {- let mut stdout = child.stdout.take().unwrap();let mut output_str = String::new();let mut buffer = [0u8; 1024];- if codex_out_file.is_none() {+ if let Some(mut stdout) = child.stdout.take() {while let Ok(n) = stdout.read(&mut buffer).await {if n == 0 {break;diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex bac5ae04..6e8556be 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -20,6 +20,10 @@ pub enum RuntimeEvent {tool_name: String,details: Value,},+ /// A pending approval can no longer be answered (its turn ended, or it expired).+ ApprovalWithdrawn {+ id: String,+ },TurnComplete {tokens: usize,duration_ms: u64,diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 79c8e98b..2f3c2ae8 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -26,6 +26,10 @@ use std::path::PathBuf;use std::sync::Arc;use std::time::Duration;use tokio::sync::{broadcast, Mutex};+use tokio_util::sync::CancellationToken;++/// How long `finish_turn` waits for cancelled in-flight calls to release the turn's servers.+const CLOSE_GRACE: Duration = Duration::from_secs(10);/// 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);@@ -43,11 +47,13 @@ pub struct PermissionSession {pub cwd: Option<PathBuf>,/// The gateway's connections to the kwant's servers, opened on first use.gateway: Arc<Mutex<Option<Arc<McpToolSession>>>>,+ /// Cancelled when the turn ends: calls still waiting (for a card) give up.+ ended: CancellationToken,}impl PermissionSession {pub fn new(kwant_id: String, kwant_name: String, turn_id: String, ctx: McpTurnContext, cwd: Option<PathBuf>) -> Self {- Self { kwant_id, kwant_name, turn_id, ctx, cwd, gateway: Default::default() }+ Self { kwant_id, kwant_name, turn_id, ctx, cwd, gateway: Default::default(), ended: CancellationToken::new() }}fn caller(&self) -> Caller {@@ -55,10 +61,14 @@ impl PermissionSession {}/// Connects to the kwant's servers once per turn; later requests reuse the connections.- async fn tool_session(&self) -> Arc<McpToolSession> {+ /// `None` once the turn has ended, so a late request can't start servers again.+ async fn tool_session(&self) -> Option<Arc<McpToolSession>> {let mut slot = self.gateway.lock().await;+ if self.ended.is_cancelled() {+ return None;+ }if let Some(open) = slot.as_ref() {- return open.clone();+ return Some(open.clone());}let cwd = self.cwd.as_deref().filter(|d| d.exists());let (session, problems) = McpToolSession::open(&self.ctx, cwd).await;@@ -67,19 +77,42 @@ impl PermissionSession {}let session = Arc::new(session);*slot = Some(session.clone());- session+ Some(session)}- /// Closes the gateway's connections (stdio servers are stopped).+ /// Ends the turn: calls still waiting give up (their cards are withdrawn), then the+ /// gateway's connections close (stdio servers are stopped).async fn close(&self) {- let Some(open) = self.gateway.lock().await.take() else { return };- // A call still in flight keeps its reference; its servers stop when that call drops it- if let Ok(session) = Arc::try_unwrap(open) {- session.shutdown().await;+ self.ended.cancel();+ let Some(mut open) = self.gateway.lock().await.take() else { return };+ // Cancelled calls drop their reference as they unwind+ let deadline = tokio::time::Instant::now() + CLOSE_GRACE;+ loop {+ match Arc::try_unwrap(open) {+ Ok(session) => return session.shutdown().await,+ Err(still_shared) if tokio::time::Instant::now() < deadline => {+ open = still_shared;+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ // Its servers stop (kill_on_drop) when the last call drops it+ Err(_) => return tracing::warn!(kwant = %self.kwant_name, "MCP gateway call outlived its turn"),+ }}}}+/// The record of a call the turn ended under, while it waited for its card.+fn cancelled_record(id: &str, tool_name: &str, server: &str, tool: &str, arguments: &Value) -> Value {+ json!({+ "id": id,+ "name": tool_name,+ "server": server,+ "tool": tool,+ "arguments": arguments,+ "status": "cancelled",+ })+}+/// 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 {@@ -94,6 +127,7 @@ struct TicketGuard {id: Option<String>,broker: PermissionBroker,db: Database,+ events: broadcast::Sender<RuntimeEvent>,}impl Drop for TicketGuard {@@ -101,10 +135,11 @@ impl Drop for TicketGuard {let (Some(id), Ok(handle)) = (self.id.take(), tokio::runtime::Handle::try_current()) else {return;};- let (broker, db) = (self.broker.clone(), self.db.clone());+ let (broker, db, events) = (self.broker.clone(), self.db.clone(), self.events.clone());handle.spawn(async move {if broker.cancel(&id).await {let _ = db.update_approval_status(&id, "cancelled").await;+ let _ = events.send(RuntimeEvent::ApprovalWithdrawn { id });}});}@@ -149,7 +184,12 @@ impl ToolApprover for BrokerApprover {details: details.clone(),}).await;- let mut guard = TicketGuard { id: Some(ticket.clone()), broker: self.broker.clone(), db: self.db.clone() };+ let mut guard = TicketGuard {+ id: Some(ticket.clone()),+ broker: self.broker.clone(),+ db: self.db.clone(),+ events: self.events.clone(),+ };let _ = self.events.send(RuntimeEvent::ApprovalRequired {id: ticket.clone(),tool_name: req.tool_name.clone(),@@ -166,8 +206,10 @@ impl ToolApprover for BrokerApprover {}Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => false,Err(_) => {- self.broker.cancel(&ticket).await;- let _ = self.db.update_approval_status(&ticket, "expired").await;+ if self.broker.cancel(&ticket).await {+ let _ = self.db.update_approval_status(&ticket, "expired").await;+ let _ = self.events.send(RuntimeEvent::ApprovalWithdrawn { id: ticket });+ }false}}@@ -255,19 +297,23 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {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;+ let approval = 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(),+ });+ // Dropping the approval withdraws its card when the turn ends first+ let allowed = tokio::select! {+ allowed = approval => allowed,+ _ = session.ended.cancelled() => {+ session.ctx.record(cancelled_record(&tool_use_id, tool_name, server, tool, &input));+ return json!({"behavior": "deny", "message": "The turn ended before the user answered."});+ }+ };session.ctx.record(json!({"id": tool_use_id,"name": tool_name,@@ -362,15 +408,31 @@ pub async fn gateway_endpoint(State(state): State<AppState>, headers: HeaderMap,}),),"ping" => rpc_result(id, json!({})),- "tools/list" => rpc_result(id, json!({"tools": session.tool_session().await.gateway_tools()})),+ "tools/list" => match session.tool_session().await {+ Some(tools) => rpc_result(id, json!({"tools": tools.gateway_tools()})),+ None => StatusCode::UNAUTHORIZED.into_response(),+ },"tools/call" => {let Some(name) = msg["params"]["name"].as_str() else {return rpc_error(id, -32602, "missing tool name");};let arguments = msg["params"].get("arguments").cloned().unwrap_or_else(|| json!({}));let call_id = format!("gw_{}", uuid::Uuid::new_v4().simple());- let tools = session.tool_session().await;- let outcome = tools.call(&session.caller(), &call_id, &format!("mcp__{name}"), &arguments.to_string()).await;+ let Some(tools) = session.tool_session().await else {+ return StatusCode::UNAUTHORIZED.into_response();+ };+ let tool_name = format!("mcp__{name}");+ // Dropping the call withdraws its card (or stops the forwarded call) when the turn ends+ let (caller, raw_arguments) = (session.caller(), arguments.to_string());+ let outcome = tokio::select! {+ outcome = tools.call(&caller, &call_id, &tool_name, &raw_arguments) => outcome,+ _ = session.ended.cancelled() => {+ let (server, tool) = mcp::split_tool_name(&tool_name).unwrap_or(("", name));+ session.ctx.record(cancelled_record(&call_id, &tool_name, server, tool, &arguments));+ drop(tools);+ return rpc_result(id, json!({"content": [{"type": "text", "text": "The turn ended before the call finished."}], "isError": true}));+ }+ };rpc_result(id,json!({"content": [{"type": "text", "text": outcome.text}], "isError": outcome.status != "ok"}),diff --git a/src/server/routes.rs b/src/server/routes.rsindex 6a46e8e8..a6110518 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1208,8 +1208,13 @@ pub async fn resolve_approval(ApprovalDecision::Deny => "denied",};- let _ = state.db.update_approval_status(&ticket_id, status_str).await;+ // Only a ticket still waiting can be answered; a withdrawn one (turn ended, expired)+ // keeps its status and its tool never runslet resolved = state.broker.resolve(&ticket_id, decision).await;+ if !resolved {+ return Err(StatusCode::CONFLICT);+ }+ let _ = state.db.update_approval_status(&ticket_id, status_str).await;Ok(Json(json!({"ticket_id": ticket_id,diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rsindex f98ea0e3..90789117 100644--- a/tests/mcp_gateway_test.rs+++ b/tests/mcp_gateway_test.rs@@ -208,3 +208,94 @@ async fn gateway_calls_wait_for_the_approval_card() {client.shutdown().await;mcp_runtime::finish_turn(&state, "card-tok").await;}++/// Pids of live processes whose environment holds `marker`.+#[cfg(target_os = "linux")]+fn processes_with_env(marker: &str) -> Vec<String> {+ let mut found = Vec::new();+ for entry in std::fs::read_dir("/proc").unwrap().flatten() {+ let pid = entry.file_name().to_string_lossy().into_owned();+ if !pid.chars().all(|c| c.is_ascii_digit()) {+ continue;+ }+ let zombie = std::fs::read_to_string(entry.path().join("stat")).map_or(true, |s| s.contains(") Z "));+ let env = std::fs::read(entry.path().join("environ")).unwrap_or_default();+ if !zombie && String::from_utf8_lossy(&env).contains(marker) {+ found.push(pid);+ }+ }+ found+}++#[cfg(target_os = "linux")]+#[tokio::test]+async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {+ let (state, _tmp) = state().await;+ let base = serve(state.clone()).await;+ let approver = Arc::new(BrokerApprover {+ db: state.db.clone(),+ broker: state.broker.clone(),+ events: state.event_sender.clone(),+ timeout: Duration::from_secs(300),+ });+ let marker = format!("KWNT_TEST_MARK_{}", uuid::Uuid::new_v4().simple());+ let mut server = echo_server();+ server.env.insert(marker.clone(), "1".into());+ let ctx = McpTurnContext {+ servers: vec![server],+ approver,+ config_dir: std::env::temp_dir(),+ permission_url: None,+ gateway: None,+ max_tool_iterations: 8,+ records: Default::default(),+ };+ state+ .mcp_sessions+ .lock()+ .await+ .insert("end-tok".into(), PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), ctx.clone(), None));+ let mut events = state.event_sender.subscribe();++ let client = McpClient::connect(&gateway(&base, Some("end-tok")), None).await.unwrap();+ let call = tokio::spawn(async move {+ let out = client.call_tool("echo__echo", json!({"text": "never"})).await;+ (client, out)+ });+ let ticket = loop {+ match tokio::time::timeout(Duration::from_secs(10), events.recv()).await.unwrap().unwrap() {+ RuntimeEvent::ApprovalRequired { id, .. } => break id,+ _ => continue,+ }+ };+ assert_eq!(processes_with_env(&marker).len(), 1, "the echo server runs while the card waits");++ // The turn ends (cancelled) while the card is still up: nothing waits out the 300 s timeout+ tokio::time::timeout(Duration::from_secs(5), mcp_runtime::finish_turn(&state, "end-tok")).await.expect("finish_turn hung");+ let (mut client, out) = tokio::time::timeout(Duration::from_secs(5), call).await.unwrap().unwrap();+ let out = out.unwrap();+ assert!(out.is_error && out.text.contains("turn ended"), "{out:?}");+ client.shutdown().await;+ assert!(processes_with_env(&marker).is_empty(), "echo server outlived the turn");++ // The card is withdrawn, and a late Allow neither runs the tool nor rewrites the ticket+ let withdrawn = loop {+ match tokio::time::timeout(Duration::from_secs(5), events.recv()).await.unwrap().unwrap() {+ RuntimeEvent::ApprovalWithdrawn { id } => break id,+ _ => continue,+ }+ };+ assert_eq!(withdrawn, ticket);+ let late = reqwest::Client::new()+ .post(format!("{base}/api/approvals/{ticket}/resolve"))+ .json(&json!({"decision": "allow_once"}))+ .send()+ .await+ .unwrap();+ assert_eq!(late.status(), reqwest::StatusCode::CONFLICT);+ assert_eq!(state.db.get_approval(&ticket).await.unwrap().unwrap().status, "cancelled");+ let records = ctx.take_records();+ assert_eq!(records.len(), 1, "{records:?}");+ assert_eq!(records[0]["status"], "cancelled");+ assert!(records[0].get("result").is_none());+}diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex a72ece58..e84eeb81 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -332,16 +332,33 @@ async fn claude_cli_gets_mcp_config_without_secrets_in_argv() {assert!(plain.contains("--strict-mcp-config") && !plain.contains("--mcp-config") && !plain.contains("permission-prompt"), "{plain}");}+/// The servers the fake codex reports for `codex mcp list --json`: a quoted name, and one+/// named like kwnt's gateway.+const USER_SERVERS: &str = r#"[{"name":"userdummy","enabled":true},{"name":"user.dot \"q\"","enabled":true},{"name":"kwnt","enabled":true}]"#;+/// Runs a fake codex/grok that logs its argv and whether it got the gateway token env, and-/// returns (argv, token env, thinking notes).-async fn fake_agent_run(kind: &str, mcp: Option<McpTurnContext>) -> (String, String, Vec<String>) {+/// returns (argv, token env, thinking notes, reply). `mcp_list` is what it prints for+/// `mcp list --json`; `None` makes that listing fail.+async fn fake_agent_run(kind: &str, mcp: Option<McpTurnContext>, mcp_list: Option<&str>) -> (String, String, Vec<String>, String) {let dir = tempdir().unwrap();let script = dir.path().join(kind);let log = dir.path().join("argv");let env_log = dir.path().join("env");+ let list = dir.path().join("list.json");+ let list_cmd = match mcp_list {+ Some(json) => {+ std::fs::write(&list, json).unwrap();+ format!("cat {}; exit 0", list.display())+ }+ None => "exit 3".to_string(),+ };std::fs::write(&script,- format!("#!/bin/sh\necho \"$*\" > {}\necho \"${{KWNT_MCP_GATEWAY_TOKEN:-unset}}\" > {}\n", log.display(), env_log.display()),+ format!(+ "#!/bin/sh\nif [ \"$1 $2 $3\" = \"mcp list --json\" ]; then {list_cmd}; fi\necho \"$*\" > {}\necho \"${{KWNT_MCP_GATEWAY_TOKEN:-unset}}\" > {}\n",+ log.display(),+ env_log.display()+ ),).unwrap();#[cfg(unix)]@@ -360,38 +377,100 @@ async fn fake_agent_run(kind: &str, mcp: Option<McpTurnContext>) -> (String, Str}notes});- driver.stream_turn(turn(mcp), tx).await.unwrap();+ let out = driver.stream_turn(turn(mcp), tx).await.unwrap();let notes = drain.await.unwrap();- (std::fs::read_to_string(&log).unwrap(), std::fs::read_to_string(&env_log).unwrap().trim().to_string(), notes)+ let read = |p: &std::path::Path| std::fs::read_to_string(p).unwrap_or_default().trim().to_string();+ (read(&log), read(&env_log), notes, out.text)}#[cfg(target_os = "linux")]#[tokio::test]async fn codex_cli_reaches_mcp_only_through_kwnts_gateway() {let tmp = tempdir().unwrap();- let (argv, token, notes) = fake_agent_run("codex", Some(ctx(tmp.path(), Arc::new(FixedApprover(true))))).await;+ let (argv, token, notes, _) =+ fake_agent_run("codex", Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), Some(USER_SERVERS)).await;+ // The user's own servers are switched off by (quoted) name; their "kwnt" is overridden, not disabledassert!(- argv.contains(r#"-c mcp_servers={kwnt={url="http://127.0.0.1:1/api/mcp/gateway",bearer_token_env_var="KWNT_MCP_GATEWAY_TOKEN",default_tools_approval_mode="approve",startup_timeout_sec=45,tool_timeout_sec=330}}"#),+ argv.contains(r#"-c mcp_servers={kwnt={url="http://127.0.0.1:1/api/mcp/gateway",bearer_token_env_var="KWNT_MCP_GATEWAY_TOKEN",default_tools_approval_mode="approve",startup_timeout_sec=45,tool_timeout_sec=330},"userdummy"={enabled=false},"user.dot \"q\""={enabled=false}} "#),"{argv}");+ assert!(argv.contains(r#"-c shell_environment_policy.set.KWNT_MCP_GATEWAY_TOKEN="""#), "token not blanked for codex's shell: {argv}");assert_eq!(token, "gw-secret-token", "token comes through the env");for secret in ["gw-secret-token", "sk-very-secret", "hdr-secret", "/usr/bin/true", "mcp.example.test"] {assert!(!argv.contains(secret), "{secret} in argv: {argv}");}assert!(!notes.iter().any(|n| n.contains("can't offer MCP tools")), "{notes:?}");- // Without servers codex still gets no MCP servers at all, not even the user's own- let (plain, token, _) = fake_agent_run("codex", None).await;- assert!(plain.contains("-c mcp_servers={} "), "{plain}");+ // Without servers (none assigned, or the kwant opted out) codex still gets none of the user's+ let (plain, token, _, _) = fake_agent_run("codex", None, Some(USER_SERVERS)).await;+ assert!(plain.contains(r#"-c mcp_servers={"userdummy"={enabled=false},"user.dot \"q\""={enabled=false}} "#), "{plain}");+ assert!(!plain.contains("shell_environment_policy"), "{plain}");assert_eq!(token, "unset");++ // And with no user servers either, the override is empty, as before+ let (bare, _, _, _) = fake_agent_run("codex", None, Some("[]")).await;+ assert!(bare.contains("-c mcp_servers={} "), "{bare}");+}++#[cfg(target_os = "linux")]+#[tokio::test]+async fn codex_cli_does_not_run_when_its_servers_cannot_be_listed() {+ let tmp = tempdir().unwrap();+ for mcp in [Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), None] {+ for list in [None, Some("not json"), Some(r#"[{"enabled":true}]"#)] {+ let (argv, _, _, reply) = fake_agent_run("codex", mcp.clone(), list).await;+ assert_eq!(argv, "", "codex exec ran: {argv}");+ assert!(reply.contains("didn't run codex"), "{reply}");+ }+ }}#[cfg(target_os = "linux")]#[tokio::test]async fn grok_cli_still_runs_without_mcp() {let tmp = tempdir().unwrap();- let (argv, token, notes) = fake_agent_run("grok", Some(ctx(tmp.path(), Arc::new(FixedApprover(true))))).await;+ let (argv, token, notes, _) = fake_agent_run("grok", Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), Some(USER_SERVERS)).await;assert_eq!(token, "unset");assert!(!argv.contains("gateway"), "{argv}");assert!(notes.iter().any(|n| n.contains("can't offer MCP tools through the grok CLI")), "{notes:?}");}++/// A cancelled turn aborts its driver task; the agent CLI must die with it rather than keep+/// running (and keep calling kwnt's gateway).+#[cfg(target_os = "linux")]+#[tokio::test]+async fn aborting_a_cli_turn_kills_the_cli() {+ let dir = tempdir().unwrap();+ let script = dir.path().join("codex");+ let pid_file = dir.path().join("pid");+ std::fs::write(+ &script,+ format!("#!/bin/sh\nif [ \"$1\" = mcp ]; then echo '[]'; exit 0; fi\necho $$ > {}\nexec sleep 60\n", pid_file.display()),+ )+ .unwrap();+ {+ 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);+ tokio::spawn(async move { while rx.recv().await.is_some() {} });+ let task = tokio::spawn(async move { driver.stream_turn(turn(None), tx).await });++ let pid = loop {+ if let Some(pid) = std::fs::read_to_string(&pid_file).ok().filter(|p| p.ends_with('\n')) {+ break pid.trim().to_string();+ }+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ };+ task.abort();+ let _ = task.await;+ let alive = || std::fs::read_to_string(format!("/proc/{pid}/stat")).map_or(false, |s| !s.contains(") Z "));+ for _ in 0..100 {+ if !alive() {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ }+ panic!("codex (pid {pid}) outlived its aborted turn");+}