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.

Claude CLI built-in tools: web lookups and in-folder writes run, shell and outside writes ask

Lin (kwant bot)f5fa8f92a40a
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 765e2432..39e75973 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -162,6 +162,22 @@ const CODEX_MCP_LIST_TIMEOUT: Duration = Duration::from_secs(15);
/// `codex exec` overrides limiting the model's shell commands to codex's "core" env
/// (PATH, HOME, USER, SHELL...). codex's default passes its whole env, provider key included.
+/// grok's headless mode refuses anything it would ask about. Like claude's policy (see
+/// `mcp::builtin_tools`): fetching pages anywhere, and editing files inside the bot's working
+/// folder, run without asking. Shell commands stay refused: grok has no approval hook for kwnt.
+pub fn grok_builtin_rules(folder: Option<&Path>) -> Vec<String> {
+ let mut rules = vec!["--allow".to_string(), "WebFetch".to_string()];
+ // grok matches paths lexically, so the folder's real path keeps a symlinked folder working
+ if let Some(dir) = folder.and_then(|d| d.canonicalize().ok()) {
+ let dir = dir.display().to_string().replace(')', "\\)");
+ for tool in ["Edit", "Write"] {
+ rules.push("--allow".into());
+ rules.push(format!("{tool}({dir}/**)"));
+ }
+ }
+ rules
+}
+
pub const CODEX_SHELL_POLICY: [&str; 4] = [
"-c",
"shell_environment_policy.inherit=\"core\"",
@@ -502,6 +518,7 @@ impl CliDriver {
args.push("--allow".into());
args.push(super::grok::gateway_allow_rule());
}
+ args.extend(grok_builtin_rules(input.workspace_dir.as_deref()));
args.push("--output-format".into());
args.push("streaming-json".into());
let gateway_token = gateway.map(|(_, g)| g.token.clone());
@@ -770,6 +787,11 @@ impl Driver for CliDriver {
.arg(codex_mcp_servers(input.mcp.as_ref(), &user_servers))
// The model's shell sees only codex's core env, never kwnt's keys or rc exports
.args(CODEX_SHELL_POLICY);
+ // codex exec has no approval hook: its sandbox keeps file writes (and shell
+ // commands' writes) inside the bot's working folder instead of read-only everywhere
+ if input.workspace_dir.as_deref().is_some_and(|d| d.exists()) {
+ cmd.arg("--sandbox").arg("workspace-write");
+ }
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
@@ -879,7 +901,14 @@ impl Driver for CliDriver {
}
}
}
- cmd.arg("--append-system-prompt").arg(&system_prompt);
+ // claude's own tools follow kwnt's policy (see mcp::builtin_tools); tell the bot
+ let folder = input.workspace_dir.as_deref().filter(|d| d.exists());
+ let tools_block = if input.mcp.is_some() {
+ crate::mcp::builtin_tools::prompt_block(folder)
+ } else {
+ String::new()
+ };
+ cmd.arg("--append-system-prompt").arg(format!("{system_prompt}{tools_block}"));
// One JSON result: tells a usage limit or sign-out apart from a reply
cmd.arg("--output-format").arg("json");
cmd.arg("-p").arg(&effective_prompt);
@@ -1018,6 +1047,16 @@ mod tests {
use super::*;
use crate::db::models::{Kwant, Message};
+ #[test]
+ fn grok_may_fetch_pages_and_edit_only_inside_the_folder() {
+ assert_eq!(grok_builtin_rules(None), ["--allow", "WebFetch"]);
+ let tmp = tempfile::tempdir().unwrap();
+ let real = tmp.path().canonicalize().unwrap().display().to_string();
+ let rules = grok_builtin_rules(Some(tmp.path()));
+ assert_eq!(rules, ["--allow", "WebFetch", "--allow", &format!("Edit({real}/**)"), "--allow", &format!("Write({real}/**)")]);
+ assert!(!rules.iter().any(|r| r.starts_with("Bash")), "shell commands stay refused");
+ }
+
#[test]
fn codex_shell_policy_is_core_only() {
let args = CODEX_SHELL_POLICY.join(" ");
diff --git a/src/mcp/builtin_tools.rs b/src/mcp/builtin_tools.rs
new file mode 100644
index 00000000..da8224f3
--- /dev/null
+++ b/src/mcp/builtin_tools.rs
@@ -0,0 +1,190 @@
+//! What a claude CLI bot may do with claude's own (built-in) tools. claude asks kwnt before each
+//! tool it would otherwise prompt for; kwnt answers from this policy:
+//! - looking things up (web search, fetching pages, reading and searching inside the bot's
+//! working folder, its own to-do list and sub-agents) runs without asking;
+//! - writing files runs without asking inside the working folder, and needs the person's OK
+//! anywhere else;
+//! - reading outside the working folder, shell commands and any tool kwnt doesn't know need the
+//! person's OK (an approval card, where "Always this session" is honoured).
+
+use serde_json::Value;
+use std::path::{Component, Path, PathBuf};
+
+/// How kwnt answers one built-in tool call.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum BuiltinDecision {
+ Allow,
+ /// Show the person an approval card. `outside_folder` is set for file tools whose path is
+ /// outside the bot's working folder (or when the bot has none).
+ Ask { outside_folder: bool },
+}
+
+/// Tools that only look things up, and touch no files.
+const LOOKUP_TOOLS: &[&str] = &["WebSearch", "WebFetch", "TodoWrite", "TodoRead", "Task", "Agent", "BashOutput", "ExitPlanMode", "ToolSearch"];
+/// Tools that read files: free inside the working folder.
+const READ_TOOLS: &[&str] = &["Read", "Glob", "Grep", "LS", "NotebookRead"];
+/// Tools that write files: free inside the working folder.
+const WRITE_TOOLS: &[&str] = &["Write", "Edit", "MultiEdit", "NotebookEdit"];
+
+/// The policy for `tool` with `input`, for a bot working in `folder` (canonical, or `None`).
+pub fn decide(tool: &str, input: &Value, folder: Option<&Path>) -> BuiltinDecision {
+ if LOOKUP_TOOLS.contains(&tool) {
+ return BuiltinDecision::Allow;
+ }
+ let reads = READ_TOOLS.contains(&tool);
+ if reads || WRITE_TOOLS.contains(&tool) {
+ let inside = match (folder, target_path(input)) {
+ (Some(folder), Some(path)) => is_inside(folder, &path),
+ // A read with no path searches the working folder itself
+ (Some(_), None) => reads,
+ (None, _) => false,
+ };
+ return if inside { BuiltinDecision::Allow } else { BuiltinDecision::Ask { outside_folder: true } };
+ }
+ // Bash and anything this version of kwnt doesn't know about
+ BuiltinDecision::Ask { outside_folder: false }
+}
+
+/// The file or folder a file tool acts on.
+fn target_path(input: &Value) -> Option<String> {
+ ["file_path", "notebook_path", "path"]
+ .iter()
+ .find_map(|k| input.get(*k).and_then(Value::as_str))
+ .map(str::trim)
+ .filter(|p| !p.is_empty())
+ .map(str::to_string)
+}
+
+/// The canonical working folder a bot's file tools are measured against.
+pub fn canonical_folder(folder: Option<&Path>) -> Option<PathBuf> {
+ folder.and_then(|f| f.canonicalize().ok())
+}
+
+/// Whether `path` (absolute, or relative to `folder`) is `folder` or inside it, once symlinks
+/// are followed. A path that doesn't exist yet is judged by its nearest existing parent, and
+/// never by a `..` in its unwritten part. A `~` path counts as outside: a tool may expand it.
+pub fn is_inside(folder: &Path, path: &str) -> bool {
+ if path.starts_with('~') {
+ return false;
+ }
+ let p = Path::new(path);
+ let joined = if p.is_absolute() { p.to_path_buf() } else { folder.join(p) };
+ match resolve(&joined) {
+ Some(real) => real.starts_with(folder),
+ None => false,
+ }
+}
+
+/// Follows symlinks through the existing part of `path` and appends the rest, refusing a `..`
+/// (or anything but a plain name) in the part that doesn't exist yet.
+fn resolve(path: &Path) -> Option<PathBuf> {
+ let mut existing = path.to_path_buf();
+ let mut rest: Vec<std::ffi::OsString> = Vec::new();
+ loop {
+ if let Ok(real) = existing.canonicalize() {
+ let mut out = real;
+ for part in rest.iter().rev() {
+ out.push(part);
+ }
+ return Some(out);
+ }
+ // A dangling symlink would be followed on write: its target is unknown, so refuse
+ if existing.symlink_metadata().is_ok() {
+ return None;
+ }
+ let name = match existing.components().next_back()? {
+ Component::Normal(name) => name.to_os_string(),
+ _ => return None,
+ };
+ rest.push(name);
+ existing = existing.parent()?.to_path_buf();
+ }
+}
+
+/// The paragraph a claude CLI bot reads about its own tools.
+pub fn prompt_block(folder: Option<&Path>) -> String {
+ let place = match folder {
+ Some(f) => format!("Your working folder is {}. You can create, edit and delete files there without asking.", f.display()),
+ None => "You have no working folder this turn, so every file write needs the person's OK.".to_string(),
+ };
+ format!(
+ "\n\n[Your tools]\nYou can search the web (WebSearch) and read web pages (WebFetch) whenever it helps; cite the pages you used. \
+ {place} Writing or reading files outside it, and every shell command (Bash), shows the person an approval card first: \
+ ask for what you need and wait for their answer instead of giving up. If they deny it, say what you would have done."
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn folder() -> (tempfile::TempDir, PathBuf) {
+ let tmp = tempfile::tempdir().unwrap();
+ let ws = tmp.path().join("ws");
+ std::fs::create_dir_all(ws.join("src")).unwrap();
+ let canon = ws.canonicalize().unwrap();
+ (tmp, canon)
+ }
+
+ #[test]
+ fn lookups_run_without_asking() {
+ for tool in ["WebSearch", "WebFetch", "TodoWrite", "Task"] {
+ assert_eq!(decide(tool, &json!({"url": "https://x"}), None), BuiltinDecision::Allow, "{tool}");
+ }
+ }
+
+ #[test]
+ fn writes_inside_the_folder_run_and_outside_ask() {
+ let (tmp, ws) = folder();
+ let inside = ws.join("src/new.go").display().to_string();
+ assert_eq!(decide("Write", &json!({"file_path": inside}), Some(&ws)), BuiltinDecision::Allow);
+ assert_eq!(decide("Edit", &json!({"file_path": "src/a.go"}), Some(&ws)), BuiltinDecision::Allow);
+ assert_eq!(decide("NotebookEdit", &json!({"notebook_path": "n.ipynb"}), Some(&ws)), BuiltinDecision::Allow);
+ let outside = tmp.path().join("other.txt").display().to_string();
+ for tool in ["Write", "Edit", "MultiEdit"] {
+ assert_eq!(decide(tool, &json!({"file_path": outside}), Some(&ws)), BuiltinDecision::Ask { outside_folder: true }, "{tool}");
+ }
+ // No folder, or no path: ask
+ assert_eq!(decide("Write", &json!({"file_path": inside}), None), BuiltinDecision::Ask { outside_folder: true });
+ assert_eq!(decide("Write", &json!({}), Some(&ws)), BuiltinDecision::Ask { outside_folder: true });
+ }
+
+ #[test]
+ fn dot_dot_and_symlinks_cannot_escape() {
+ let (tmp, ws) = folder();
+ for sneaky in ["../escape.txt", "src/../../escape.txt", "new/../../escape.txt", "/etc/passwd", "~/.ssh/id_rsa"] {
+ assert!(!is_inside(&ws, sneaky), "{sneaky}");
+ }
+ // A not-yet-written path is judged by its existing parent
+ assert!(is_inside(&ws, "src/deep/new/file.rs"));
+ #[cfg(unix)]
+ {
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir_all(&outside).unwrap();
+ std::os::unix::fs::symlink(&outside, ws.join("link")).unwrap();
+ assert!(!is_inside(&ws, "link/file.txt"), "a symlink out of the folder is outside");
+ std::os::unix::fs::symlink(tmp.path().join("nowhere"), ws.join("dangling")).unwrap();
+ assert!(!is_inside(&ws, "dangling"), "a dangling symlink is refused");
+ std::os::unix::fs::symlink(ws.join("src"), ws.join("inner")).unwrap();
+ assert!(is_inside(&ws, "inner/ok.rs"), "a symlink within the folder stays inside");
+ }
+ }
+
+ #[test]
+ fn reads_are_free_inside_and_ask_outside() {
+ let (tmp, ws) = folder();
+ assert_eq!(decide("Read", &json!({"file_path": "src/x.rs"}), Some(&ws)), BuiltinDecision::Allow);
+ assert_eq!(decide("Grep", &json!({"pattern": "fn"}), Some(&ws)), BuiltinDecision::Allow);
+ assert_eq!(decide("Glob", &json!({"pattern": "**/*.rs", "path": ws.display().to_string()}), Some(&ws)), BuiltinDecision::Allow);
+ let secret = tmp.path().join(".ssh/id_rsa").display().to_string();
+ assert_eq!(decide("Read", &json!({"file_path": secret}), Some(&ws)), BuiltinDecision::Ask { outside_folder: true });
+ }
+
+ #[test]
+ fn shell_and_unknown_tools_ask() {
+ let (_tmp, ws) = folder();
+ assert_eq!(decide("Bash", &json!({"command": "ls"}), Some(&ws)), BuiltinDecision::Ask { outside_folder: false });
+ assert_eq!(decide("SomeFutureTool", &json!({}), Some(&ws)), BuiltinDecision::Ask { outside_folder: false });
+ }
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index af1c14e4..2792c342 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 builtin_tools;
pub mod cli_config;
pub mod client;
pub mod echo_server;
@@ -255,6 +256,17 @@ pub struct ToolApprovalRequest {
pub server: String,
pub tool: String,
pub arguments: Value,
+ /// Set for one of claude's own tools (Bash, Write, …) rather than an MCP server's.
+ pub builtin: Option<BuiltinCall>,
+}
+
+/// Where a built-in tool call would act, for its approval card.
+#[derive(Debug, Clone, Serialize)]
+pub struct BuiltinCall {
+ /// The bot's working folder (the shell command's folder for Bash).
+ pub cwd: Option<String>,
+ /// The file tool's path is outside the working folder.
+ pub outside_folder: bool,
}
/// Decides whether an MCP tool call may run. The server implements it with the permission broker.
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 8fef1a1c..2e8f77a4 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -242,6 +242,7 @@ impl McpToolSession {
server: server.clone(),
tool: t.tool.name.clone(),
arguments: arguments.clone(),
+ builtin: None,
})
.await;
if !approved {
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 9d4e297e..2fdf2d52 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -151,14 +151,25 @@ impl ToolApprover for BrokerApprover {
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 details = match &req.builtin {
+ Some(b) => json!({
+ "source": "claude_builtin",
+ "tool": req.tool,
+ "arguments": req.arguments,
+ "cwd": b.cwd,
+ "outside_folder": b.outside_folder,
+ "kwant_id": req.kwant_id,
+ "kwant_name": req.kwant_name,
+ }),
+ None => 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 {
@@ -317,17 +328,31 @@ 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.
+/// Answers one claude permission prompt. MCP tools from the kwant's own servers get their
+/// approval card; claude's own tools follow [`mcp::builtin_tools`]; tools from servers the
+/// kwant doesn't have are denied.
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 bot.")});
+ let (server, tool, builtin) = match mcp::split_tool_name(tool_name) {
+ Some((server, tool)) if session.ctx.servers.iter().any(|s| s.name == server) => (server, tool, None),
+ _ if tool_name.is_empty() || tool_name.starts_with("mcp__") => {
+ return json!({"behavior": "deny", "message": format!("{tool_name} is not available to this bot.")});
+ }
+ _ => {
+ let folder = mcp::builtin_tools::canonical_folder(session.cwd.as_deref());
+ match mcp::builtin_tools::decide(tool_name, &input, folder.as_deref()) {
+ mcp::builtin_tools::BuiltinDecision::Allow => {
+ return json!({"behavior": "allow", "updatedInput": input});
+ }
+ mcp::builtin_tools::BuiltinDecision::Ask { outside_folder } => {
+ let cwd = folder.or_else(|| session.cwd.clone()).map(|f| f.display().to_string());
+ ("", tool_name, Some(mcp::BuiltinCall { cwd, outside_folder }))
+ }
+ }
+ }
};
let approval = session.ctx.approver.approve(ToolApprovalRequest {
kwant_id: session.kwant_id.clone(),
@@ -337,6 +362,7 @@ async fn decide(session: &PermissionSession, args: &Value) -> Value {
server: server.to_string(),
tool: tool.to_string(),
arguments: input.clone(),
+ builtin,
});
// Dropping the approval withdraws its card when the turn ends first
let allowed = tokio::select! {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 2460efca..83fcddd9 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1124,6 +1124,11 @@ async fn run_kwant_turn_inner(
let kwant_id = scope.kwant_id.clone();
let team_keys = &scope.team_keys;
let cancel_token = &scope.cancel_token;
+ // A bot outside a team still gets a folder of its own to write files in
+ let workspace_dir = scope.workspace_dir.clone().or_else(|| {
+ let space = SpaceId::new(&target_kwant.space_id);
+ Some(crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), &target_kwant.id))
+ });
{
let space = SpaceId::new(&target_kwant.space_id);
@@ -1312,7 +1317,7 @@ async fn run_kwant_turn_inner(
}),
cancel: Some(cancel_token.clone()),
turn_id: Some(tag.turn_id.clone()),
- workspace: scope.workspace_dir.clone(),
+ workspace: workspace_dir.clone(),
sandbox_target: Some(sandbox_target.clone()),
}
});
@@ -1320,7 +1325,7 @@ async fn run_kwant_turn_inner(
state,
target_kwant,
Some(tag.turn_id.clone()),
- scope.workspace_dir.clone(),
+ workspace_dir.clone(),
self_scope,
)
.await;
@@ -1350,7 +1355,7 @@ async fn run_kwant_turn_inner(
model: None,
effort_level: Some(effort_level.clone()),
team_context: scope.team_context.clone(),
- workspace_dir: scope.workspace_dir.clone(),
+ workspace_dir: workspace_dir.clone(),
sandbox_id: Some(sandbox_target.clone()),
teammates: scope
.teammates
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index 3cd7c9b0..4a7c152e 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -74,6 +74,15 @@ impl ToolRunner {
}
}
+/// The working folder of a bot outside any team: `<space data>/bot-workspaces/<kwant id>`,
+/// created on first use. Its file tools write there without asking.
+pub fn bot_workspace(space_data_dir: &std::path::Path, kwant_id: &str) -> PathBuf {
+ let safe: String = kwant_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
+ let dir = space_data_dir.join("bot-workspaces").join(safe);
+ let _ = std::fs::create_dir_all(&dir);
+ dir
+}
+
pub async fn resolve_or_prepare_workspace(
base_data_dir: &std::path::Path,
team_name: &str,
diff --git a/tests/browser_tools_test.rs b/tests/browser_tools_test.rs
index 3a58bafd..092a6902 100644
--- a/tests/browser_tools_test.rs
+++ b/tests/browser_tools_test.rs
@@ -1,6 +1,6 @@
//! The bot browser as kwnt's own MCP tools (`browser_open`, `browser_page`, `browser_act`).
-//! Claude's permission prompt refuses Bash, so the old curl instructions never reached the
-//! browser; these tools go through the self server, which needs no approval card, and drive
+//! Claude's permission prompt asks the person before Bash, so the old curl instructions were a
+//! detour; these tools go through the self server, which needs no approval card, and drive
//! only the turn's own sandbox. The browser part runs a real windowless Chrome in Local mode and
//! is skipped when none is installed.
@@ -136,8 +136,8 @@ async fn claude_turn_gets_browser_tools_that_drive_its_own_panel() {
let (text, is_error) = self_tool(&app, &bare, "browser_open", json!({"url": "http://127.0.0.1:1/"})).await;
assert!(is_error && text.contains("Unknown tool"), "{text}");
- // claude asks before every tool: Bash stays refused, the browser tools pass with no card
- assert_eq!(claude_asks(&app, &token, "Bash").await, "deny");
+ // claude asks before every tool: the browser tools (like web lookups) pass with no card
+ assert_eq!(claude_asks(&app, &token, "WebFetch").await, "allow");
assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_open")).await, "allow");
assert_eq!(claude_asks(&app, &token, &format!("mcp__{SELF_SERVER_NAME}__browser_act")).await, "allow");
assert!(state.broker.pending_ids().await.is_empty(), "no approval card for the bot's own browser");
diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rs
new file mode 100644
index 00000000..d374ae70
--- /dev/null
+++ b/tests/builtin_tools_test.rs
@@ -0,0 +1,169 @@
+//! claude's own tools through kwnt's permission prompt: lookups and writes inside the bot's
+//! working folder run without a card; writes outside it and shell commands show the person an
+//! approval card ("Always this session" is honoured); tools from servers the bot doesn't have
+//! are refused.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ drivers::events::RuntimeEvent,
+ mcp::PERMISSION_TOOL,
+ router::LayaRouter,
+ server::{continuity::SelfScope, create_router, mcp_runtime, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ (create_router(state.clone()), state, tmp)
+}
+
+async fn post(app: &Router, uri: &str, body: Value) -> (StatusCode, Value) {
+ let req = Request::builder().method("POST").uri(uri).header("content-type", "application/json");
+ let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+/// What claude's `--permission-prompt-tool` asks kwnt before running a tool.
+async fn claude_asks(app: &Router, token: &str, tool_name: &str, input: Value) -> Value {
+ let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {
+ "name": PERMISSION_TOOL, "arguments": {"tool_name": tool_name, "input": input, "tool_use_id": "u1"},
+ }});
+ let (status, v) = post(app, &format!("/api/mcp/permission/{token}"), call).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ serde_json::from_str(v["result"]["content"][0]["text"].as_str().unwrap()).unwrap()
+}
+
+/// The next approval card shown: its id and details.
+async fn next_card(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> (String, Value) {
+ loop {
+ match tokio::time::timeout(Duration::from_secs(5), events.recv()).await.expect("no approval card").unwrap() {
+ RuntimeEvent::ApprovalRequired { id, details, .. } => return (id, details),
+ _ => continue,
+ }
+ }
+}
+
+#[tokio::test]
+async fn built_in_tools_follow_the_folder_policy() {
+ let (app, state, tmp) = setup().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let folder = tmp.path().join("ws");
+ std::fs::create_dir_all(&folder).unwrap();
+ let real = folder.canonicalize().unwrap();
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&state, &bot, None, Some(folder.clone()), Some(scope)).await.unwrap();
+ let mut events = state.event_sender.subscribe();
+
+ // Looking things up and writing inside the folder: no card
+ for (tool, input) in [
+ ("WebSearch", json!({"query": "sma crossover"})),
+ ("WebFetch", json!({"url": "https://example.com", "prompt": "summary"})),
+ ("Write", json!({"file_path": real.join("strategy.go").display().to_string(), "content": "package x"})),
+ ("Edit", json!({"file_path": "strategy.go", "old_string": "x", "new_string": "y"})),
+ ("Read", json!({"file_path": "strategy.go"})),
+ ] {
+ let d = claude_asks(&app, &token, tool, input.clone()).await;
+ assert_eq!(d, json!({"behavior": "allow", "updatedInput": input}), "{tool}");
+ }
+ assert!(state.broker.pending_ids().await.is_empty(), "no card for lookups or in-folder writes");
+
+ // Writing outside the folder (or escaping it with ..) shows a card; Deny refuses it
+ let outside = tmp.path().join("elsewhere.txt").display().to_string();
+ for path in [outside.clone(), "../elsewhere.txt".to_string()] {
+ let ask = tokio::spawn({
+ let (app, token) = (app.clone(), token.clone());
+ async move { claude_asks(&app, &token, "Write", json!({"file_path": path, "content": "x"})).await }
+ });
+ let (id, details) = next_card(&mut events).await;
+ assert_eq!(details["source"], "claude_builtin");
+ assert_eq!(details["tool"], "Write");
+ assert_eq!(details["outside_folder"], true);
+ assert_eq!(details["cwd"], real.display().to_string());
+ let (status, _) = post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(ask.await.unwrap()["behavior"], "deny");
+ }
+
+ // A shell command shows a card with the command and folder; Allow once runs it once
+ let bash = |cmd: &str| json!({"command": cmd, "description": "List files"});
+ let ask = tokio::spawn({
+ let (app, token, input) = (app.clone(), token.clone(), bash("ls"));
+ async move { claude_asks(&app, &token, "Bash", input).await }
+ });
+ let (id, details) = next_card(&mut events).await;
+ assert_eq!(details["source"], "claude_builtin");
+ assert_eq!(details["arguments"]["command"], "ls");
+ assert_eq!(details["outside_folder"], false);
+ assert_eq!(details["cwd"], real.display().to_string());
+ assert_eq!(details["kwant_name"], bot.name);
+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "allow_once"})).await;
+ assert_eq!(ask.await.unwrap(), json!({"behavior": "allow", "updatedInput": bash("ls")}));
+
+ // Always this session: the next command runs without a card
+ let ask = tokio::spawn({
+ let (app, token, input) = (app.clone(), token.clone(), bash("go test ./..."));
+ async move { claude_asks(&app, &token, "Bash", input).await }
+ });
+ let (id, _) = next_card(&mut events).await;
+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;
+ assert_eq!(ask.await.unwrap()["behavior"], "allow");
+ assert_eq!(claude_asks(&app, &token, "Bash", bash("ls -la")).await["behavior"], "allow");
+ assert!(state.broker.pending_ids().await.is_empty(), "always-this-session skips the card");
+
+ // A tool kwnt doesn't know asks too; servers the bot doesn't have are refused outright
+ let ask = tokio::spawn({
+ let (app, token) = (app.clone(), token.clone());
+ async move { claude_asks(&app, &token, "SomeNewTool", json!({})).await }
+ });
+ let (id, details) = next_card(&mut events).await;
+ assert_eq!(details["tool"], "SomeNewTool");
+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;
+ assert_eq!(ask.await.unwrap()["behavior"], "deny");
+ for tool in ["mcp__other__echo", "mcp__kwnt__approve", ""] {
+ assert_eq!(claude_asks(&app, &token, tool, json!({})).await["behavior"], "deny", "{tool}");
+ }
+ assert!(state.broker.pending_ids().await.is_empty());
+ mcp_runtime::finish_turn(&state, &token).await;
+}
+
+#[tokio::test]
+async fn without_a_folder_every_write_asks() {
+ let (app, state, _tmp) = setup().await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_ctx, token) = mcp_runtime::prepare_turn_with_self(&state, &bot, None, None, Some(scope)).await.unwrap();
+ let mut events = state.event_sender.subscribe();
+ let ask = tokio::spawn({
+ let (app, token) = (app.clone(), token.clone());
+ async move { claude_asks(&app, &token, "Write", json!({"file_path": "/tmp/x.txt", "content": "x"})).await }
+ });
+ let (id, details) = next_card(&mut events).await;
+ assert_eq!(details["outside_folder"], true);
+ assert!(details["cwd"].is_null());
+ // The turn ending withdraws the card and denies the call
+ mcp_runtime::finish_turn(&state, &token).await;
+ assert_eq!(ask.await.unwrap()["behavior"], "deny");
+ assert!(!state.broker.is_pending(&id).await);
+}
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index c5754446..13ca02b9 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -691,6 +691,7 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {
server: server.into(),
tool: "x".into(),
arguments: json!({}),
+ builtin: None,
};
assert!(
ctx.approver.approve(approve(SELF_SERVER_NAME)).await,
diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rs
index 3f6d5eaf..5f7c3411 100644
--- a/tests/mcp_runtime_test.rs
+++ b/tests/mcp_runtime_test.rs
@@ -75,6 +75,7 @@ fn request(tool: &str) -> ToolApprovalRequest {
server: "echo".into(),
tool: tool.into(),
arguments: json!({"text": "hi"}),
+ builtin: None,
}
}
@@ -233,8 +234,11 @@ async fn permission_endpoint_answers_claude_prompts_over_http() {
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"] {
+ // claude's own tools follow the built-in policy: Bash asks the approver (here: yes)
+ let bash: Value = serde_json::from_str(&client.call_tool("approve", ask("Bash")).await.unwrap().text).unwrap();
+ assert_eq!(bash["behavior"], "allow");
+ // Servers the kwant doesn't have are refused without asking
+ for tool in ["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}");
}
@@ -248,10 +252,11 @@ async fn permission_endpoint_answers_claude_prompts_over_http() {
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.len(), 2, "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!(allow_records[1]["name"], "Bash");
assert_eq!(sessions["deny-tok"].ctx.take_records()[0]["status"], "denied");
drop(sessions);
@@ -464,7 +469,7 @@ async fn grok_cli_reaches_mcp_only_through_kwnts_gateway() {
let tmp = tempdir().unwrap();
let (argv, token, notes, _) = fake_agent_run("grok", Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), Some(USER_SERVERS)).await;
assert_eq!(token, "gw-secret-token", "token comes through the env");
- assert!(argv.contains("--allow MCPTool(kwnt__*) --output-format streaming-json"), "{argv}");
+ assert!(argv.contains("--allow MCPTool(kwnt__*) --allow WebFetch --output-format streaming-json"), "{argv}");
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}");
}