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 tools for codex kwants through a per-turn kwnt MCP gateway

Lin (kwant bot)0c58ce9aca79
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 2eefb6f6..c7529d04 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -155,8 +155,17 @@ Body: `{"server_ids": ["…"]}` (replaces the whole assignment; `[]` clears it).
(`--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.
+- **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
+ on 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.
+ `grok` CLI agents do not get MCP servers yet: its config overlay (`GROK_CONFIG_PATH`) cannot
+ add `mcp_servers`, and it has no per-run MCP flag.
- **API agents** (OpenAI-compatible chat endpoints, incl. Ollama): kwnt connects to the servers,
offers their tools in the `tools` field, executes `tool_calls` and feeds results back, for at
most `mcp_max_tool_iterations` model calls per turn (setting or env
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 1afc56a3..5d3ba3c5 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -70,6 +70,32 @@ fn find_cli_binary_uncached(name: &str) -> Option<String> {
None
}
+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();
+ };
+ 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,
+ )
+}
+
pub fn build_cli_prompt(input: &TurnInput) -> String {
if input.history.is_empty() {
return input.prompt.clone();
@@ -172,7 +198,7 @@ impl Driver for CliDriver {
cmd.env("BROWSER", "none");
cmd.env("DISPLAY", "");
- if input.mcp.is_some() && matches!(self.tool_kind.as_str(), "codex" | "grok") {
+ if input.mcp.is_some() && self.tool_kind == "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.",
@@ -197,11 +223,14 @@ 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
+ // Never the user's own config.toml servers: codex exec has no hook for kwnt's
+ // approval cards. The kwant's servers come only through kwnt's gateway.
.arg("-c")
- .arg("mcp_servers={}")
- .arg("-o")
+ .arg(codex_mcp_servers(input.mcp.as_ref()));
+ if let Some(gateway) = input.mcp.as_ref().and_then(|c| c.gateway.as_ref()) {
+ cmd.env(crate::mcp::GATEWAY_TOKEN_ENV, &gateway.token);
+ }
+ cmd.arg("-o")
.arg(&out_file)
.arg(&full_prompt);
codex_out_file = Some(out_file);
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index c7dd54c1..492e80e1 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -31,6 +31,8 @@ pub const RECORD_RESULT_MAX_CHARS: usize = 4000;
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";
+/// Env variable that hands an agent CLI its turn's gateway token (never put in argv).
+pub const GATEWAY_TOKEN_ENV: &str = "KWNT_MCP_GATEWAY_TOKEN";
/// API representation of a server: secrets replaced by [`SECRET_MASK`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -278,11 +280,26 @@ pub struct McpTurnContext {
pub config_dir: PathBuf,
/// kwnt's permission-prompt MCP endpoint for this turn (claude CLI only).
pub permission_url: Option<String>,
+ /// kwnt's MCP gateway for this turn, for agent CLIs that can't route approvals themselves.
+ pub gateway: Option<GatewayAccess>,
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>>>,
}
+/// Where an agent CLI reaches this turn's MCP gateway. The token is sent as a bearer token.
+#[derive(Clone)]
+pub struct GatewayAccess {
+ pub url: String,
+ pub token: String,
+}
+
+impl std::fmt::Debug for GatewayAccess {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GatewayAccess").field("url", &self.url).field("token", &"<redacted>").finish()
+ }
+}
+
impl McpTurnContext {
pub fn record(&self, record: Value) {
if let Ok(mut r) = self.records.lock() {
@@ -305,6 +322,7 @@ impl std::fmt::Debug for McpTurnContext {
.field("servers", &self.servers)
.field("config_dir", &self.config_dir)
.field("permission_url", &self.permission_url.as_ref().map(|_| "<set>"))
+ .field("gateway", &self.gateway)
.field("max_tool_iterations", &self.max_tool_iterations)
.finish()
}
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 88b5a583..ff8d3136 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -103,6 +103,25 @@ impl McpToolSession {
.collect()
}
+ /// The `tools/list` result for kwnt's MCP gateway. Tools are named `<server>__<tool>`, so an
+ /// agent CLI that prefixes `mcp__kwnt__` still shows which server a tool belongs to.
+ pub fn gateway_tools(&self) -> Vec<Value> {
+ self.tools
+ .iter()
+ .map(|t| {
+ let mut schema = t.tool.input_schema.clone();
+ if !schema.is_object() {
+ schema = json!({"type": "object", "properties": {}});
+ }
+ json!({
+ "name": t.name.strip_prefix("mcp__").unwrap_or(&t.name),
+ "description": t.tool.description.clone().unwrap_or_default(),
+ "inputSchema": schema,
+ })
+ })
+ .collect()
+ }
+
/// Runs one model-requested call: approval first, then the MCP call. The record is also
/// appended to the turn's `tool_calls`.
pub async fn call(&self, caller: &Caller, call_id: &str, name: &str, raw_arguments: &str) -> CallOutcome {
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 0c23aec0..79c8e98b 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -1,37 +1,83 @@
//! 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.
+//! approval cards as API agents. Agent CLIs with no permission hook (codex) instead reach the
+//! kwant's servers through kwnt's MCP gateway, which asks for approval before forwarding each call.
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 crate::mcp::{
+ self,
+ client::PROTOCOL_VERSION,
+ session::{Caller, McpToolSession},
+ GatewayAccess, McpTurnContext, ToolApprovalRequest, ToolApprover,
+};
use async_trait::async_trait;
use axum::{
extract::{Path, State},
- http::StatusCode,
+ http::{header::AUTHORIZATION, HeaderMap, StatusCode},
response::{IntoResponse, Response},
Json,
};
use serde_json::{json, Value};
+use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
-use tokio::sync::broadcast;
+use tokio::sync::{broadcast, Mutex};
/// 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.
+/// An agent CLI turn whose permission prompts (claude) or gateway calls (codex) kwnt answers.
#[derive(Clone)]
pub struct PermissionSession {
pub kwant_id: String,
pub kwant_name: String,
pub turn_id: String,
pub ctx: McpTurnContext,
+ /// Working directory for the kwant's stdio servers when the gateway starts them.
+ pub cwd: Option<PathBuf>,
+ /// The gateway's connections to the kwant's servers, opened on first use.
+ gateway: Arc<Mutex<Option<Arc<McpToolSession>>>>,
+}
+
+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() }
+ }
+
+ fn caller(&self) -> Caller {
+ Caller { kwant_id: self.kwant_id.clone(), kwant_name: self.kwant_name.clone(), turn_id: self.turn_id.clone() }
+ }
+
+ /// Connects to the kwant's servers once per turn; later requests reuse the connections.
+ async fn tool_session(&self) -> Arc<McpToolSession> {
+ let mut slot = self.gateway.lock().await;
+ if let Some(open) = slot.as_ref() {
+ return open.clone();
+ }
+ let cwd = self.cwd.as_deref().filter(|d| d.exists());
+ let (session, problems) = McpToolSession::open(&self.ctx, cwd).await;
+ for problem in problems {
+ tracing::warn!(kwant = %self.kwant_name, %problem, "MCP gateway could not reach a server");
+ }
+ let session = Arc::new(session);
+ *slot = Some(session.clone());
+ session
+ }
+
+ /// Closes the gateway's connections (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;
+ }
+ }
}
/// Asks the user through the permission broker: stores the ticket, emits `ApprovalRequired`
@@ -147,9 +193,10 @@ fn local_base_url(state: &AppState) -> String {
}
/// 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)> {
+/// session claude's permission prompts and codex's gateway calls reach. Returns `None` (no
+/// behaviour change) otherwise. `cwd` is where the gateway starts stdio servers. Pair with
+/// [`finish_turn`].
+pub async fn prepare_turn(state: &AppState, kwant: &Kwant, cwd: Option<PathBuf>) -> Option<(McpTurnContext, String)> {
let mut servers = match state.db.list_active_mcp_servers_for_kwant(&kwant.id).await {
Ok(s) if !s.is_empty() => s,
Ok(_) => return None,
@@ -172,21 +219,20 @@ pub async fn prepare_turn(state: &AppState, kwant: &Kwant) -> Option<(McpTurnCon
}),
config_dir: state.config.data_dir.join("mcp"),
permission_url: Some(format!("{}/api/mcp/permission/{token}", local_base_url(state))),
+ gateway: Some(GatewayAccess { url: format!("{}/api/mcp/gateway", local_base_url(state)), token: token.clone() }),
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(),
- };
+ let session = PermissionSession::new(kwant.id.clone(), kwant.name.clone(), uuid::Uuid::new_v4().to_string(), ctx.clone(), cwd);
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);
+ let session = state.mcp_sessions.lock().await.remove(token);
+ if let Some(session) = session {
+ session.close().await;
+ }
}
fn rpc_result(id: Value, result: Value) -> Response {
@@ -284,3 +330,52 @@ pub async fn permission_endpoint(
_ => rpc_error(id, -32601, "method not found"),
}
}
+
+fn bearer_token(headers: &HeaderMap) -> Option<&str> {
+ let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
+ let (scheme, token) = value.split_once(' ')?;
+ scheme.eq_ignore_ascii_case("bearer").then(|| token.trim()).filter(|t| !t.is_empty())
+}
+
+/// `POST /api/mcp/gateway`: a streamable-HTTP MCP server (JSON responses) that offers the
+/// kwant's servers' tools to an agent CLI. The turn is picked by its bearer token, so the token
+/// stays out of URLs and argv. Every call is approved through the turn's approver (the
+/// approval card) before it is forwarded, and recorded like any other MCP call.
+pub async fn gateway_endpoint(State(state): State<AppState>, headers: HeaderMap, Json(msg): Json<Value>) -> Response {
+ let session = match bearer_token(&headers) {
+ Some(token) => state.mcp_sessions.lock().await.get(token).cloned(),
+ None => None,
+ };
+ let Some(session) = session else {
+ return StatusCode::UNAUTHORIZED.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": session.tool_session().await.gateway_tools()})),
+ "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;
+ rpc_result(
+ id,
+ json!({"content": [{"type": "text", "text": outcome.text}], "isError": outcome.status != "ok"}),
+ )
+ }
+ _ => rpc_error(id, -32601, "method not found"),
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index c0d3eed1..c69be68b 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -117,6 +117,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/mcp/oauth/callback", get(mcp_oauth::callback))
.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/mcp/gateway", post(mcp_runtime::gateway_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 b424ed54..6a46e8e8 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -668,7 +668,7 @@ 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_turn = super::mcp_runtime::prepare_turn(&state, &target_kwant, scope.workspace_dir.clone()).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)),
diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rs
index 82635c64..704f2415 100644
--- a/tests/mcp_api_loop_test.rs
+++ b/tests/mcp_api_loop_test.rs
@@ -70,6 +70,7 @@ fn ctx(approver: Arc<dyn ToolApprover>, timeout_secs: i64, max: usize) -> McpTur
approver,
config_dir: std::env::temp_dir(),
permission_url: None,
+ gateway: None,
max_tool_iterations: max,
records: Default::default(),
}
diff --git a/tests/mcp_default_on_test.rs b/tests/mcp_default_on_test.rs
index 0558ebd3..50d78fbb 100644
--- a/tests/mcp_default_on_test.rs
+++ b/tests/mcp_default_on_test.rs
@@ -63,7 +63,7 @@ async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (St
async fn turn_servers(state: &AppState, kwant_id: &str) -> Vec<String> {
let kwant = state.db.get_kwant(kwant_id).await.unwrap().unwrap();
- match mcp_runtime::prepare_turn(state, &kwant).await {
+ match mcp_runtime::prepare_turn(state, &kwant, None).await {
Some((ctx, token)) => {
let names = ctx.servers.iter().map(|s| s.name.clone()).collect();
mcp_runtime::finish_turn(state, &token).await;
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
new file mode 100644
index 00000000..f98ea0e3
--- /dev/null
+++ b/tests/mcp_gateway_test.rs
@@ -0,0 +1,210 @@
+//! kwnt's MCP gateway: the per-turn streamable-HTTP endpoint codex reaches the kwant's servers
+//! through. Every call is approved by kwnt (the approval card) before it is forwarded.
+
+use kwnt::{
+ broker::{ApprovalDecision, PermissionBroker},
+ config::Config,
+ db::{models::McpServer, Database},
+ drivers::events::RuntimeEvent,
+ mcp::{FixedApprover, McpClient, McpTurnContext, ToolApprover},
+ router::LayaRouter,
+ server::{
+ create_router,
+ mcp_runtime::{self, BrokerApprover, PermissionSession},
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::json;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+
+const KWNT: &str = env!("CARGO_BIN_EXE_kwnt");
+
+fn echo_server() -> 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: 10,
+ created_at: None,
+ }
+}
+
+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)
+}
+
+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}")
+}
+
+/// Registers a turn whose gateway calls are decided by `approver`.
+async fn register(state: &AppState, token: &str, approver: Arc<dyn ToolApprover>) -> McpTurnContext {
+ let ctx = McpTurnContext {
+ servers: vec![echo_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(
+ token.into(),
+ PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), ctx.clone(), None),
+ );
+ ctx
+}
+
+/// The gateway as codex sees it: an http MCP server with a bearer token header.
+fn gateway(base: &str, token: Option<&str>) -> McpServer {
+ McpServer {
+ id: "kwnt".into(),
+ name: "kwnt".into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: Some(format!("{base}/api/mcp/gateway")),
+ env: BTreeMap::new(),
+ headers: token.map(|t| BTreeMap::from([("Authorization".to_string(), format!("Bearer {t}"))])).unwrap_or_default(),
+ enabled: true,
+ timeout_secs: 10,
+ created_at: None,
+ }
+}
+
+#[tokio::test]
+async fn gateway_lists_the_kwants_tools_and_forwards_approved_calls() {
+ let (state, _tmp) = state().await;
+ let base = serve(state.clone()).await;
+ let ctx = register(&state, "allow-tok", Arc::new(FixedApprover(true))).await;
+
+ let mut client = McpClient::connect(&gateway(&base, Some("allow-tok")), None).await.unwrap();
+ assert_eq!(client.server_info["name"], "kwnt");
+ let tools = client.list_tools().await.unwrap();
+ let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
+ assert!(names.contains(&"echo__echo") && names.contains(&"echo__add"), "{names:?}");
+ let echo = tools.iter().find(|t| t.name == "echo__echo").unwrap();
+ assert_eq!(echo.input_schema["required"], json!(["text"]));
+
+ let out = client.call_tool("echo__echo", json!({"text": "hello gateway"})).await.unwrap();
+ assert!(!out.is_error);
+ assert_eq!(out.text, "hello gateway");
+ // Server secrets never reach the agent
+ let secret = client.call_tool("echo__env", json!({"name": "ECHO_SECRET"})).await.unwrap();
+ assert!(!secret.text.contains("hunter2-secret"), "{}", secret.text);
+ // Tools the kwant doesn't have are refused
+ let unknown = client.call_tool("other__echo", json!({})).await.unwrap();
+ assert!(unknown.is_error);
+ client.shutdown().await;
+
+ let records = ctx.take_records();
+ assert_eq!(records[0]["name"], "mcp__echo__echo");
+ assert_eq!(records[0]["server"], "echo");
+ assert_eq!(records[0]["status"], "ok");
+ assert_eq!(records[0]["result"], "hello gateway");
+ mcp_runtime::finish_turn(&state, "allow-tok").await;
+}
+
+#[tokio::test]
+async fn gateway_denied_call_returns_no_output() {
+ let (state, _tmp) = state().await;
+ let base = serve(state.clone()).await;
+ let ctx = register(&state, "deny-tok", Arc::new(FixedApprover(false))).await;
+
+ let mut client = McpClient::connect(&gateway(&base, Some("deny-tok")), None).await.unwrap();
+ let out = client.call_tool("echo__echo", json!({"text": "must not run"})).await.unwrap();
+ assert!(out.is_error);
+ assert_eq!(out.text, "The user denied this tool call.");
+ client.shutdown().await;
+
+ let records = ctx.take_records();
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0]["status"], "denied");
+ assert!(records[0].get("result").is_none());
+ mcp_runtime::finish_turn(&state, "deny-tok").await;
+}
+
+#[tokio::test]
+async fn gateway_rejects_missing_wrong_and_finished_tokens() {
+ let (state, _tmp) = state().await;
+ let base = serve(state.clone()).await;
+ register(&state, "live-tok", Arc::new(FixedApprover(true))).await;
+
+ assert!(McpClient::connect(&gateway(&base, None), None).await.is_err(), "no token");
+ assert!(McpClient::connect(&gateway(&base, Some("wrong-tok")), None).await.is_err(), "wrong token");
+ let status = reqwest::Client::new()
+ .post(format!("{base}/api/mcp/gateway"))
+ .header("Authorization", "Basic live-tok")
+ .json(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}))
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(status, 401, "only bearer tokens");
+ // The token never works as a path segment
+ assert!(McpClient::connect(&gateway(&format!("{base}/api/mcp/gateway/live-tok"), None), None).await.is_err());
+
+ assert!(McpClient::connect(&gateway(&base, Some("live-tok")), None).await.is_ok());
+ mcp_runtime::finish_turn(&state, "live-tok").await;
+ assert!(McpClient::connect(&gateway(&base, Some("live-tok")), None).await.is_err(), "finished turn");
+}
+
+#[tokio::test]
+async fn gateway_calls_wait_for_the_approval_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(10),
+ });
+ register(&state, "card-tok", approver).await;
+ let mut events = state.event_sender.subscribe();
+
+ let client = McpClient::connect(&gateway(&base, Some("card-tok")), None).await.unwrap();
+ let call = tokio::spawn(async move {
+ let out = client.call_tool("echo__echo", json!({"text": "after approval"})).await;
+ (client, out)
+ });
+ let ticket = loop {
+ match tokio::time::timeout(Duration::from_secs(10), events.recv()).await.unwrap().unwrap() {
+ RuntimeEvent::ApprovalRequired { id, tool_name, details } => {
+ assert_eq!(tool_name, "mcp__echo__echo");
+ assert_eq!(details["kwant_name"], "Ada");
+ assert_eq!(details["arguments"]["text"], "after approval");
+ break id;
+ }
+ _ => continue,
+ }
+ };
+ assert!(!call.is_finished(), "the call must wait for the user");
+ state.broker.resolve(&ticket, ApprovalDecision::AllowOnce).await;
+ let (mut client, out) = call.await.unwrap();
+ assert_eq!(out.unwrap().text, "after approval");
+ client.shutdown().await;
+ mcp_runtime::finish_turn(&state, "card-tok").await;
+}
diff --git a/tests/mcp_oauth_test.rs b/tests/mcp_oauth_test.rs
index 46ff6a3c..94928af5 100644
--- a/tests/mcp_oauth_test.rs
+++ b/tests/mcp_oauth_test.rs
@@ -171,7 +171,7 @@ async fn sign_in_flow_end_to_end() {
// Turns get the Bearer header; the claude CLI config carries it in its private file
let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();
e.state.db.set_kwant_mcp_servers(&kwant.id, &[id.clone()]).await.unwrap();
- let (ctx, turn) = mcp_runtime::prepare_turn(&e.state, &kwant).await.unwrap();
+ let (ctx, turn) = mcp_runtime::prepare_turn(&e.state, &kwant, None).await.unwrap();
let bearer = format!("Bearer {}", token.access_token);
assert_eq!(ctx.servers[0].headers["Authorization"], bearer);
assert!(ctx.secret_values().contains(&bearer), "token is redacted from tool output");
@@ -215,7 +215,7 @@ async fn short_lived_tokens_are_refreshed_before_use() {
// Concurrent turns refresh once each in turn, never with a spent refresh token
let kwant = e.state.db.list_kwants().await.unwrap().into_iter().next().unwrap();
e.state.db.set_kwant_mcp_servers(&kwant.id, &[id.clone()]).await.unwrap();
- let (a, b) = tokio::join!(mcp_runtime::prepare_turn(&e.state, &kwant), mcp_runtime::prepare_turn(&e.state, &kwant));
+ let (a, b) = tokio::join!(mcp_runtime::prepare_turn(&e.state, &kwant, None), mcp_runtime::prepare_turn(&e.state, &kwant, None));
for (ctx, _) in [a.unwrap(), b.unwrap()] {
assert!(ctx.servers[0].headers["Authorization"].starts_with("Bearer at-"));
}
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index 259f4d35..a72ece58 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -6,7 +6,7 @@ use kwnt::{
db::{models::McpServer, Database},
db::models::Kwant,
drivers::{events::RuntimeEvent, CliDriver, Driver, TurnInput},
- mcp::{cli_config, FixedApprover, McpClient, McpTurnContext, ToolApprovalRequest, ToolApprover},
+ mcp::{cli_config, FixedApprover, GatewayAccess, McpClient, McpTurnContext, ToolApprovalRequest, ToolApprover},
router::LayaRouter,
server::{create_router, mcp_runtime::{BrokerApprover, PermissionSession}, AppState},
tools::ToolRunner,
@@ -46,6 +46,7 @@ fn ctx(dir: &std::path::Path, approver: Arc<dyn ToolApprover>) -> McpTurnContext
approver,
config_dir: dir.join("mcp"),
permission_url: Some("http://127.0.0.1:1/api/mcp/permission/tok".into()),
+ gateway: Some(GatewayAccess { url: "http://127.0.0.1:1/api/mcp/gateway".into(), token: "gw-secret-token".into() }),
max_tool_iterations: 8,
records: Default::default(),
}
@@ -218,7 +219,7 @@ async fn permission_endpoint_answers_claude_prompts_over_http() {
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 },
+ PermissionSession::new("k1".into(), "Ada".into(), "t1".into(), c, None),
);
}
@@ -331,21 +332,24 @@ 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}");
}
-#[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
+/// 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>) {
let dir = tempdir().unwrap();
- let script = dir.path().join("codex");
+ let script = dir.path().join(kind);
let log = dir.path().join("argv");
- std::fs::write(&script, format!("#!/bin/sh\necho \"$*\" > {}\n", log.display())).unwrap();
+ let env_log = dir.path().join("env");
+ std::fs::write(
+ &script,
+ format!("#!/bin/sh\necho \"$*\" > {}\necho \"${{KWNT_MCP_GATEWAY_TOKEN:-unset}}\" > {}\n", log.display(), env_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 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 {
let mut notes = Vec::new();
@@ -356,9 +360,38 @@ async fn codex_cli_runs_with_mcp_disabled() {
}
notes
});
- driver.stream_turn(turn(Some(ctx(tmp.path(), Arc::new(FixedApprover(true))))), tx).await.unwrap();
+ driver.stream_turn(turn(mcp), 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:?}");
+ (std::fs::read_to_string(&log).unwrap(), std::fs::read_to_string(&env_log).unwrap().trim().to_string(), notes)
+}
+
+#[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;
+ assert!(
+ 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}"
+ );
+ 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}");
+ assert_eq!(token, "unset");
+}
+
+#[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;
+ 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:?}");
}