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.

45.0 KB
Raw Blame
//! 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 cli_hooks;
pub mod client;
pub mod composio;
pub mod declined;
pub mod echo_server;
pub mod fetch_risk;
pub mod home_floor;
pub mod media;
pub mod oauth;
pub mod payment_floor;
pub mod prod_floor;
pub mod oauth_mock;
pub mod directory;
pub mod registry;
pub mod repeat_guard;
pub mod session;
pub mod shell_risk;

pub use client::{McpClient, McpError, McpTool};
pub use oauth::OAuthStatus;

use crate::db::models::McpServer;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

/// Shown in place of every secret value; sending it back on update keeps the stored value.
pub const SECRET_MASK: &str = "********";
/// Server name kwnt uses for its own permission endpoint in agent CLI configs.
pub const RESERVED_SERVER_NAME: &str = "kwnt";
/// What a driver says (as a thinking line) when one of the turn's servers could not be reached
/// at the start: `"MCP server unavailable: <server>: <why>"` (read by `server::tool_failures`).
pub const UNAVAILABLE_PREFIX: &str = "MCP server unavailable: ";
/// Server name of the agents' own continuity tools (`mcp__kwnt_tools__memory_add`, …).
pub const SELF_SERVER_NAME: &str = "kwnt_tools";
pub const DEFAULT_TIMEOUT_SECS: i64 = 30;
/// Model calls an API-driver turn may make for tools; routines and delegations also get one
/// automatic continuation when a turn runs out (see `routes::continue_once_if_capped`).
pub const DEFAULT_MAX_TOOL_ITERATIONS: usize = 25;
/// Longest tool result kept in a message's `tool_calls` record.
pub const RECORD_RESULT_MAX_CHARS: usize = 4000;
/// How long a tool call waits for the person's approval card. After that the call is `unanswered`:
/// it didn't run, the card stays open (a late Allow starts a new turn to make it) and the bot is told so.
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)]
pub struct McpServerView {
    pub id: String,
    pub name: String,
    pub transport: String,
    pub command: Option<String>,
    pub args: Vec<String>,
    pub url: Option<String>,
    pub env: BTreeMap<String, String>,
    pub headers: BTreeMap<String, String>,
    pub enabled: bool,
    pub timeout_secs: i64,
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
    /// OAuth sign-in status (http servers); filled in by the routes, never contains tokens.
    #[serde(default)]
    pub oauth: OAuthStatus,
    /// Kwants that have this server switched off; every other kwant gets it. Filled in by the routes.
    #[serde(default)]
    pub disabled_for_kwants: Vec<String>,
}

impl From<&McpServer> for McpServerView {
    fn from(s: &McpServer) -> Self {
        let mask = |m: &BTreeMap<String, String>| m.keys().map(|k| (k.clone(), SECRET_MASK.to_string())).collect();
        Self {
            id: s.id.clone(),
            name: s.name.clone(),
            transport: s.transport.clone(),
            command: s.command.clone(),
            args: s.args.clone(),
            url: s.url.clone(),
            env: mask(&s.env),
            headers: mask(&s.headers),
            enabled: s.enabled,
            timeout_secs: s.timeout_secs,
            created_at: s.created_at,
            oauth: OAuthStatus::default(),
            disabled_for_kwants: Vec::new(),
        }
    }
}

/// Body of create and update requests.
#[derive(Debug, Clone, Deserialize)]
pub struct McpServerInput {
    pub name: String,
    pub transport: String,
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub args: Option<Vec<String>>,
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub env: Option<BTreeMap<String, String>>,
    #[serde(default)]
    pub headers: Option<BTreeMap<String, String>>,
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub timeout_secs: Option<i64>,
}

/// A name `build_server` accepts: the shape below and not one of kwnt's own names.
pub fn usable_server_name(name: &str) -> bool {
    valid_server_name(name) && !name.eq_ignore_ascii_case(RESERVED_SERVER_NAME) && !name.eq_ignore_ascii_case(SELF_SERVER_NAME)
}

fn valid_server_name(name: &str) -> bool {
    let first_ok = name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
    first_ok
        && name.len() <= 48
        && !name.contains("__")
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

fn valid_env_key(key: &str) -> bool {
    let first_ok = key.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
    first_ok && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn valid_header_name(name: &str) -> bool {
    !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c))
}

/// Applies the masking rules: a masked value keeps the stored one, a missing map keeps them all.
fn merge_secrets(
    incoming: Option<BTreeMap<String, String>>,
    existing: Option<&BTreeMap<String, String>>,
    what: &str,
) -> Result<BTreeMap<String, String>, String> {
    let Some(incoming) = incoming else {
        return Ok(existing.cloned().unwrap_or_default());
    };
    let mut merged = BTreeMap::new();
    for (key, value) in incoming {
        if value == SECRET_MASK {
            match existing.and_then(|e| e.get(&key)) {
                Some(stored) => merged.insert(key, stored.clone()),
                None => return Err(format!("{what} '{key}' has no stored value to keep; send the real value")),
            };
        } else {
            merged.insert(key, value);
        }
    }
    Ok(merged)
}

/// Validates a create/update body and turns it into a server, merging masked secrets with
/// `existing` on update. The returned server keeps `existing`'s id and creation time.
pub fn build_server(input: McpServerInput, existing: Option<&McpServer>) -> Result<McpServer, String> {
    let name = input.name.trim().to_string();
    if !valid_server_name(&name) {
        return Err("name must be 1-48 characters of letters, digits, '_' or '-', start with a letter or digit and not contain '__'".into());
    }
    if name.eq_ignore_ascii_case(RESERVED_SERVER_NAME) || name.eq_ignore_ascii_case(SELF_SERVER_NAME) {
        return Err(format!("name '{name}' is reserved"));
    }
    let timeout_secs = input.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS);
    if !(1..=600).contains(&timeout_secs) {
        return Err("timeout_secs must be between 1 and 600".into());
    }
    let env = merge_secrets(input.env, existing.map(|e| &e.env), "env")?;
    let headers = merge_secrets(input.headers, existing.map(|e| &e.headers), "header")?;
    let command = input.command.map(|c| c.trim().to_string()).filter(|c| !c.is_empty());
    let url = input.url.map(|u| u.trim().to_string()).filter(|u| !u.is_empty());
    let args = input.args.unwrap_or_default();

    match input.transport.as_str() {
        "stdio" => {
            if command.is_none() {
                return Err("stdio servers need a command".into());
            }
            if url.is_some() {
                return Err("stdio servers take no url".into());
            }
            if !headers.is_empty() {
                return Err("headers only apply to http servers".into());
            }
            if let Some(bad) = env.keys().find(|k| !valid_env_key(k)) {
                return Err(format!("invalid env variable name '{bad}'"));
            }
        }
        "http" => {
            let Some(ref u) = url else {
                return Err("http servers need a url".into());
            };
            match reqwest::Url::parse(u) {
                Ok(parsed) if matches!(parsed.scheme(), "http" | "https") && parsed.host().is_some() => {}
                _ => return Err("url must be an http:// or https:// address".into()),
            }
            if command.is_some() || !args.is_empty() {
                return Err("http servers take no command or args".into());
            }
            if !env.is_empty() {
                return Err("env only applies to stdio servers".into());
            }
            if let Some(bad) = headers.keys().find(|k| !valid_header_name(k)) {
                return Err(format!("invalid header name '{bad}'"));
            }
        }
        _ => return Err("transport must be 'stdio' or 'http'".into()),
    }

    Ok(McpServer {
        id: existing.map(|e| e.id.clone()).unwrap_or_default(),
        name,
        transport: input.transport,
        command,
        args,
        url,
        env,
        headers,
        enabled: input.enabled.unwrap_or(true),
        timeout_secs,
        created_at: existing.and_then(|e| e.created_at),
    })
}

/// Whether stdio `server` would run a file from `folder`, its working folder (D4, C8): a program
/// or argument that is a relative path (`./x.js`, `bin/serve`, or a bare name that exists in the
/// folder, like `server.js`), or an absolute path inside the folder, including after `--opt=`.
/// In a folder an isolated bot used, such a file may be one it rewrote, so the server isn't
/// started there. A program looked up on `PATH` (`npx`, `uvx`) and paths outside are fine.
pub fn runs_folder_file(server: &McpServer, folder: &std::path::Path) -> bool {
    use std::path::Path;
    if server.transport != "stdio" {
        return false;
    }
    // The folder as given too: on Windows `canonicalize` returns a `\\?\` long-name path that a
    // typed path (8.3 short names, mixed slashes) never starts with
    let typed = folder;
    let folder = crate::db::isolated_folders::canonical(folder);
    let names_file = |word: &str, program: bool| {
        let word = word.trim();
        if word.is_empty() {
            return false;
        }
        let p = Path::new(word);
        if p.is_absolute() {
            return crate::db::isolated_folders::canonical(p).starts_with(&folder) || p.starts_with(&folder) || p.starts_with(typed);
        }
        // A program with a slash resolves from the folder; a bare one is a PATH lookup. An argument
        // names a folder file when it starts with `.` or its first part exists there (an npm
        // scope such as `@modelcontextprotocol/x` doesn't, so it stays a package name)
        if program {
            return word.contains('/') || word.starts_with('.');
        }
        let first = p.components().next().map(|c| folder.join(c)).unwrap_or_else(|| folder.clone());
        word.starts_with('.') || std::fs::symlink_metadata(first).is_ok()
    };
    let program = server.command.as_deref().unwrap_or("");
    names_file(program, true)
        || server.args.iter().any(|a| {
            // `--config=./x`: the value names a file just the same
            let value = a.split_once('=').map(|(_, v)| v);
            names_file(a, false) || value.is_some_and(|v| names_file(v, false))
        })
}

/// Makes stdio `server` start from `dir`, whatever folder its starter runs it in (D4, C8):
/// `/bin/sh -c 'cd -- "$0" && exec "$@"' <dir> <command> <args...>`. Both starters honour it:
/// kwnt's own client, which sets the folder it's given, and a CLI agent, which starts the servers
/// in its config from its own folder (that config has no folder field). A program started in a
/// folder an isolated bot used can load what the bot planted there (`python3 -m x` imports
/// `./x.py`, `npx x` runs `./node_modules/.bin/x`), so it starts from an empty folder instead.
pub fn start_in(server: &mut McpServer, dir: &std::path::Path) {
    if server.transport != "stdio" {
        return;
    }
    let Some(program) = server.command.take() else { return };
    let mut args = vec!["-c".to_string(), r#"cd -- "$0" && exec "$@""#.to_string(), dir.to_string_lossy().into_owned(), program];
    args.append(&mut server.args);
    server.command = Some("/bin/sh".into());
    server.args = args;
}

/// Replaces every non-empty secret in `text` with [`SECRET_MASK`].
pub fn redact(text: &str, secrets: &[String]) -> String {
    let mut out = text.to_string();
    let mut sorted: Vec<&String> = secrets.iter().filter(|s| !s.is_empty()).collect();
    // Longest first, so a secret containing another is masked whole
    sorted.sort_by_key(|s| std::cmp::Reverse(s.len()));
    for secret in sorted {
        out = out.replace(secret.as_str(), SECRET_MASK);
    }
    out
}

/// Cuts `text` to at most `max` characters, marking the cut.
pub fn truncate_text(text: &str, max: usize) -> String {
    match text.char_indices().nth(max) {
        Some((idx, _)) => format!("{}… [truncated]", &text[..idx]),
        None => text.to_string(),
    }
}

/// `mcp__<server>__<tool>`, the name agents see for an MCP tool.
pub fn namespaced_tool_name(server: &str, tool: &str) -> String {
    format!("mcp__{server}__{tool}")
}

/// Splits `mcp__<server>__<tool>`; server names cannot contain `__`, so the first split is right.
pub fn split_tool_name(name: &str) -> Option<(&str, &str)> {
    let rest = name.strip_prefix("mcp__")?;
    let (server, tool) = rest.split_once("__")?;
    (!server.is_empty() && !tool.is_empty()).then_some((server, tool))
}

/// One tool call waiting for the user's approval.
#[derive(Debug, Clone, Serialize)]
pub struct ToolApprovalRequest {
    pub kwant_id: String,
    pub kwant_name: String,
    pub turn_id: String,
    /// Namespaced name, e.g. `mcp__github__create_issue`.
    pub tool_name: String,
    pub server: String,
    pub tool: String,
    pub arguments: Value,
    /// Set for one of claude's own tools (Bash, Write, …) rather than an MCP server's.
    pub builtin: Option<BuiltinCall>,
    /// What "Ask only when risky" makes of this call; `None` asks. Only read when the bot's
    /// approvals are `smart`.
    pub smart: Option<SmartVerdict>,
    /// Why the caller already knows this call pays (kwnt's browser on a checkout page), for the
    /// payment floor; the approver also checks the call itself ([`payment_floor::reason`]).
    pub payment: Option<String>,
}

/// Whether a call may run without a card under "Ask only when risky", and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum SmartVerdict {
    /// Runs and is recorded as `auto_allowed`; says why it is safe.
    Allow(String),
    /// Shows the card; says what made it risky (or unreadable).
    Ask(String),
}

impl SmartVerdict {
    pub fn is_allowed(&self) -> bool {
        matches!(self, SmartVerdict::Allow(_))
    }

    pub fn reason(&self) -> &str {
        match self {
            SmartVerdict::Allow(why) | SmartVerdict::Ask(why) => why,
        }
    }
}

/// 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.
#[async_trait]
pub trait ToolApprover: Send + Sync {
    async fn approve(&self, request: ToolApprovalRequest) -> bool;

    /// [`approve`](Self::approve), telling a refusal apart from a card nobody answered in time.
    async fn decide(&self, request: ToolApprovalRequest) -> ApprovalOutcome {
        if self.approve(request).await {
            ApprovalOutcome::Allowed
        } else {
            ApprovalOutcome::Denied
        }
    }

    /// Records a decision in the task's side-effect ledger (`turn_tool_calls`): `allowed`,
    /// `auto_allowed`, `approved` or `denied`. Called for the calls the permission hook lets
    /// through on its own too. Default: nothing is recorded.
    async fn note(&self, _request: &ToolApprovalRequest, _decision: &'static str, _approval_id: Option<&str>) {}

    /// Flight School's gate (C3): `Some(reason)` when this call must get a card even where the
    /// permission hook would let it through on its own. Default: no gate.
    async fn tier_gate(&self, _request: &ToolApprovalRequest) -> Option<String> {
        None
    }

    /// The pre-push card (B2) for an MCP call that writes to a GitHub branch: `Ok` with the
    /// overridden cards it goes on and the person's grant that covers it (empty: not such a
    /// write, or nothing to use up), else the
    /// text the bot gets back instead of the call running. Asked before [`decide`](Self::decide).
    /// Default: no gate.
    async fn prepush_gate(&self, _request: &ToolApprovalRequest) -> Result<PrepushPass, String> {
        Ok(PrepushPass::default())
    }

    /// Uses up the overrides [`prepush_gate`](Self::prepush_gate) found, once the call is
    /// allowed: `None` lets it run, else the text the bot gets back. Default: nothing to use.
    async fn prepush_use(&self, _overrides: &[String]) -> Option<String> {
        None
    }

    /// [`decide`](Self::decide) for a push the person's Retry or Override on a pre-push card
    /// already approved (`grant`, 0.9.7): the ordinary approval card is skipped and the grant used
    /// up, but the payment floor, the production floor and Flight School still ask as in
    /// [`decide`](Self::decide). Default: `grant` changes nothing.
    async fn decide_granted(&self, request: ToolApprovalRequest, _grant: &PrepushGrant) -> ApprovalOutcome {
        self.decide(request).await
    }
}

/// The person's one-time approval of a bot's push, from Retry or Override on a pre-push card
/// (0.9.7, `dev_prepush_grants`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrepushGrant {
    pub id: String,
    /// `retry` or `override`.
    pub kind: String,
    /// The card the person pressed.
    pub pressed_card_id: String,
    /// The card of the push it covers (clear, or the overridden card itself).
    pub card_id: String,
}

/// What [`ToolApprover::prepush_gate`] found for a call that may run.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrepushPass {
    /// The `overridden` cards it goes on, for [`ToolApprover::prepush_use`].
    pub overrides: Vec<String>,
    /// The person's grant that covers it, for [`ToolApprover::decide_granted`].
    pub grant: Option<PrepushGrant>,
}

/// What became of a call that may have needed a card.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalOutcome {
    Allowed,
    Denied,
    /// Nobody answered before the wait ran out. The card stays open, and a late Allow starts a
    /// new turn to continue.
    Unanswered,
    /// A Skill Foundry replay (a dry run): the call didn't run and was recorded as what the bot
    /// would have done.
    Rehearsed,
    /// 27b: the person already declined a call of this kind in this chat ([`declined`]), so it was
    /// refused with no card. Recorded as `denied`.
    DeclinedBefore,
}

/// What the bot is told when the person refused a call: that, and [`NOT_ANOTHER_WAY_TEXT`].
pub const DENIED_TEXT: &str = "The user denied this tool call. Don't try it again or another way unless the person asks.";
/// 29o: the longest reason, in chars, the person can give with a Deny ([`deny_reason`]).
pub const DENY_REASON_MAX: usize = 500;

/// 29o: the person's reason on a Deny as the bot hears it: control characters (newlines, tabs)
/// and runs of spaces become one space, trimmed, cut at [`DENY_REASON_MAX`] chars. `None` when
/// nothing is left: a plain Deny.
pub fn deny_reason(raw: &str) -> Option<String> {
    let flat: String = raw.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
    let line = flat.split_whitespace().collect::<Vec<_>>().join(" ");
    let cut: String = line.chars().take(DENY_REASON_MAX).collect();
    let cut = cut.trim_end();
    (!cut.is_empty()).then(|| cut.to_string())
}

/// 29o: what the bot is told when the person refused a call and said why. Unlike
/// [`DENIED_TEXT`] it may try another way the person pointed to; that call asks again. Its first
/// sentence is [`DENIED_TEXT`]'s, word for word: the activity log pairs a CLI's denial with the
/// person's card by that sentence (28b/28q), so the step still ends "You said no; nothing ran".
pub fn denied_with_reason_text(reason: &str) -> String {
    format!(
        "The user denied this tool call. They said why: \"{reason}\". Don't make this same call again. \
If what they said points to another way, you may try that; it will ask them again. Otherwise say in your reply what you couldn't do."
    )
}

/// 29s: the detail of the card's approval step after a Deny whose reason the call heard, so the
/// person (and a teammate reading the run) can see later what they told the bot. The tool step
/// keeps [`DENIED_STEP_DETAIL`]. The activity log redacts the reason, then cuts it so this fits
/// its detail length with the closing quote kept.
pub fn said_why_detail(reason: &str) -> String {
    format!("You said why: \u{201c}{reason}\u{201d}")
}

tokio::task_local! {
    /// 29o: where [`tell_deny_reason`] leaves the person's reason for [`hear_deny_reason`].
    static DENY_REASON: Arc<Mutex<Option<String>>>;
}

/// 29o: runs `decide` (an approver's [`ToolApprover::decide`] or
/// [`decide_granted`](ToolApprover::decide_granted)) and hears the reason the person gave if they
/// denied its card with one. [`ApprovalOutcome`] stays `Copy` and every approver that wraps
/// another passes it through unchanged: the reason travels beside it, in this task only.
pub async fn hear_deny_reason<F>(decide: F) -> (ApprovalOutcome, Option<String>)
where
    F: std::future::Future<Output = ApprovalOutcome>,
{
    let slot = Arc::new(Mutex::new(None));
    let outcome = DENY_REASON.scope(slot.clone(), decide).await;
    let reason = slot.lock().ok().and_then(|mut s| s.take());
    (outcome, reason.filter(|_| outcome == ApprovalOutcome::Denied))
}

/// 29o: hands the person's reason for a Deny to the caller waiting in [`hear_deny_reason`];
/// false when nobody in this task listens (the bot then hears [`DENIED_TEXT`]).
pub fn tell_deny_reason(reason: String) -> bool {
    DENY_REASON
        .try_with(|slot| {
            if let Ok(mut s) = slot.lock() {
                *s = Some(reason);
            }
        })
        .is_ok()
}

/// 27b: the end of [`DENIED_TEXT`], for the bot only; a step's detail leaves it out.
pub const NOT_ANOTHER_WAY_TEXT: &str = "Don't try it again or another way unless the person asks.";
/// 27b: what the bot is told when kwant refused a call because the person already said no to one
/// like it in this chat ([`ApprovalOutcome::DeclinedBefore`]).
pub const DECLINED_BEFORE_TEXT: &str = "The person already said no to a call like this in this chat, so kwant didn't run it or ask again. \
Don't try it again or another way. In your reply, say what you couldn't do; if the person still wants it, they can say so in this chat and you can try again.";
/// 27b: the step detail of a call refused as [`ApprovalOutcome::DeclinedBefore`].
pub const DECLINED_BEFORE_STEP_DETAIL: &str = "You said no to a call like this earlier in this chat; kwant didn't ask again";
/// What the bot is told when nobody answered the card in time.
pub const UNANSWERED_TEXT: &str = "No one has answered the approval card for this call yet, so it did not run. \
The card stays open: if the person allows it later, you will be started again to make this same call and continue. \
Don't retry it now. Finish what you can without it, then end your turn saying what you were about to do and why.";
/// Said once per turn, with the first tool result that failed or didn't run (error, denied,
/// unanswered), so the model's final reply doesn't claim what didn't happen (26b).
pub const NO_FALSE_CLAIMS_TEXT: &str =
    "A step failed or wasn't approved. Don't say it worked or that you checked something you didn't.";
/// The step detail of a call nobody answered: the wait is [`APPROVAL_TIMEOUT_SECS`].
pub const UNANSWERED_STEP_DETAIL: &str = "Waited 5 minutes for your answer; nothing ran";
/// The step detail of a call the person said no to on its card (28b): the tool step ends
/// `declined`, in the person's words. The bot is still told [`DENIED_TEXT`].
pub const DENIED_STEP_DETAIL: &str = "You said no; nothing ran";
/// The step detail of a call kwant refused on its own, with no card the person said no on (28k):
/// kwnt's secret files, a ticket it couldn't store, a card withdrawn before anyone answered. The
/// bot is still told [`DENIED_TEXT`]; only the saved step says who stopped it.
pub const BLOCKED_STEP_DETAIL: &str = "kwant blocked this; nothing ran";
/// The step detail of a call whose card stopped waiting with no answer and couldn't stay open
/// for a late one (28k): it didn't run, and it wasn't the person's no.
pub const NOBODY_ANSWERED_STEP_DETAIL: &str = "Nobody answered in time; nothing ran";
/// The step detail of a push or GitHub write the pre-push gate held (28k). The bot still gets
/// the gate's own text, which says what to do next.
pub const PREPUSH_BLOCKED_STEP_DETAIL: &str = "Blocked before push; nothing ran";
/// The step detail of a call a Skill Foundry replay recorded instead of running.
pub const REHEARSED_STEP_DETAIL: &str = "Dry run: kwant recorded this call instead of running it";

/// Whether a tool call record's `status` means the call failed or didn't run, so the turn's
/// reply must not say it worked: `error`, `failed`, `denied`, `cancelled` or `unanswered`.
/// A `rehearsed` call (a dry run) isn't one: the bot is told to say what it would have done.
pub fn missed_status(status: &str) -> bool {
    matches!(
        status,
        "error" | "failed" | "denied" | "cancelled" | "unanswered"
    )
}

/// Whether a call that ended with record `status` gets the once-per-turn
/// [`NO_FALSE_CLAIMS_TEXT`] reminder (26b): a failed or unanswered result. A plain denial
/// doesn't: the person said no and the bot is already told so ([`DENIED_TEXT`]).
pub fn reminds(status: &str) -> bool {
    missed_status(status) && status != "denied"
}

/// `text` with [`NO_FALSE_CLAIMS_TEXT`] after it, on its own line.
pub fn with_no_false_claims(text: &str) -> String {
    format!("{}\n\n{NO_FALSE_CLAIMS_TEXT}", text.trim_end())
}

/// What the bot is told in a Skill Foundry replay when a call could change something.
pub const REHEARSED_TEXT: &str = "This is a dry run on a scratch copy of an earlier task: calls that could change \
anything outside the scratch folder (send, publish, sign in, pay, run commands, write elsewhere, other servers' tools) \
don't run. kwant recorded this one as what you would have done. Don't retry it; carry on with what you can do in \
the scratch folder, then end your turn saying what you would have done.";

impl ApprovalOutcome {
    pub fn allowed(self) -> bool {
        self == ApprovalOutcome::Allowed
    }

    /// The tool result a call that didn't run gets.
    pub fn refusal_text(self) -> &'static str {
        match self {
            ApprovalOutcome::Unanswered => UNANSWERED_TEXT,
            ApprovalOutcome::Rehearsed => REHEARSED_TEXT,
            ApprovalOutcome::DeclinedBefore => DECLINED_BEFORE_TEXT,
            _ => DENIED_TEXT,
        }
    }

    /// [`refusal_text`](Self::refusal_text), or on the person's Deny with a reason (29o)
    /// [`denied_with_reason_text`].
    pub fn refusal(self, reason: Option<&str>) -> String {
        match (self, reason) {
            (ApprovalOutcome::Denied, Some(why)) => denied_with_reason_text(why),
            _ => self.refusal_text().to_string(),
        }
    }

    /// The record status of a call that didn't run.
    pub fn record_status(self) -> &'static str {
        match self {
            ApprovalOutcome::Allowed => "allowed",
            ApprovalOutcome::Denied | ApprovalOutcome::DeclinedBefore => "denied",
            ApprovalOutcome::Unanswered => "unanswered",
            ApprovalOutcome::Rehearsed => "rehearsed",
        }
    }
}

/// Approves or denies everything; for tests and tooling.
pub struct FixedApprover(pub bool);

#[async_trait]
impl ToolApprover for FixedApprover {
    async fn approve(&self, _request: ToolApprovalRequest) -> bool {
        self.0
    }
}

/// A bot's effective approvals as its prompt describes them (`db::approval_modes`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Approvals {
    /// Every tool call that changes things shows the person a card first. Also what anything
    /// unknown, an audit turn and a read-only turn are told.
    #[default]
    Ask,
    /// "Ask only when risky": ordinary work runs, risky calls show a card.
    Smart,
    /// The person switched approvals off: tools run without a card (a payment, a Flight School tier
    /// gate or the Dev mode production floor still asks).
    Off,
}

impl Approvals {
    /// From an effective mode (`ask`, `smart`, `off`); anything else is [`Approvals::Ask`].
    pub fn from_mode(mode: &str) -> Self {
        match mode {
            crate::db::approval_modes::OFF => Self::Off,
            crate::db::approval_modes::SMART => Self::Smart,
            _ => Self::Ask,
        }
    }
}

/// What a driver needs to offer MCP tools on one turn. Only set when the kwant has servers.
#[derive(Clone)]
pub struct McpTurnContext {
    /// The kwant's enabled servers, secrets included.
    pub servers: Vec<McpServer>,
    pub approver: Arc<dyn ToolApprover>,
    /// Private directory for per-turn agent CLI config files.
    pub config_dir: PathBuf,
    /// kwnt's permission-prompt MCP endpoint for this turn (claude CLI only).
    pub permission_url: Option<String>,
    /// 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,
    /// The bot's approvals (ask, smart or off) when the turn started; only tells the bot what to
    /// expect (the approver reads the live setting for each call).
    pub approvals: Approvals,
    /// Tool call records for the reply's `tool_calls` field; drivers and the permission endpoint append.
    pub records: Arc<Mutex<Vec<Value>>>,
    /// A business customer's turn (`every_call`, B1): `servers` holds only kwnt's own, and agent
    /// CLIs run with none of their built-in tools, so their own allow rules have nothing to let
    /// through without a card. A CLI that can't be held to that runs the turn with no tools.
    pub kwnt_only: bool,
    /// 26h: where pictures, audio and video an MCP tool returns are saved and shown in the
    /// turn's chat ([`media::MediaSink`]). `None` (no chat to post into): the model is told a
    /// file came back but couldn't be saved.
    pub media: Option<Arc<dyn media::MediaSink>>,
}

/// 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 GatewayAccess {
    /// The gateway's grok naming mode (`POST /api/mcp/gateway/grok`): no `__` in tool names.
    pub fn grok_url(&self) -> String {
        format!("{}/grok", self.url.trim_end_matches('/'))
    }
}

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() {
            r.push(record);
        }
    }

    /// Whether a call this turn already failed or went unanswered (see [`reminds`]): the
    /// [`NO_FALSE_CLAIMS_TEXT`] reminder went with that one, so it isn't said again.
    pub fn had_miss(&self) -> bool {
        self.records
            .lock()
            .map(|r| {
                r.iter()
                    .any(|c| c["status"].as_str().is_some_and(reminds))
            })
            .unwrap_or(true)
    }

    pub fn take_records(&self) -> Vec<Value> {
        self.records.lock().map(|mut r| std::mem::take(&mut *r)).unwrap_or_default()
    }

    pub fn secret_values(&self) -> Vec<String> {
        self.servers.iter().flat_map(|s| s.secret_values()).collect()
    }
}

impl std::fmt::Debug for McpTurnContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpTurnContext")
            .field("servers", &self.servers)
            .field("config_dir", &self.config_dir)
            .field("permission_url", &self.permission_url.as_ref().map(|_| "<set>"))
            .field("gateway", &self.gateway)
            .field("max_tool_iterations", &self.max_tool_iterations)
            .field("media", &self.media.as_ref().map(|_| "<set>"))
            .finish()
    }
}

#[cfg(test)]
mod folder_file_tests {
    use super::*;

    fn stdio(command: &str, args: &[&str]) -> McpServer {
        McpServer {
            id: "m1".into(),
            name: "x".into(),
            transport: "stdio".into(),
            command: Some(command.into()),
            args: args.iter().map(|a| a.to_string()).collect(),
            url: None,
            env: Default::default(),
            headers: Default::default(),
            enabled: true,
            timeout_secs: 30,
            created_at: None,
        }
    }

    #[test]
    fn a_server_that_runs_a_file_from_the_folder_is_spotted() {
        let t = tempfile::tempdir().unwrap();
        let dir = t.path();
        std::fs::write(dir.join("server.js"), "").unwrap();
        std::fs::create_dir(dir.join("tools")).unwrap();
        let outside = tempfile::tempdir().unwrap();
        let abs_out = outside.path().join("srv.js");
        let abs_in = dir.join("tools/srv.js");
        for (cmd, args) in [
            ("node", vec!["server.js"]),
            ("node", vec!["./missing.js"]),
            ("./bin/serve", vec![]),
            ("bin/serve", vec![]),
            ("python3", vec!["-m", "x", "--config=./cfg.json"]),
            ("node", vec![abs_in.to_str().unwrap()]),
            (abs_in.to_str().unwrap(), vec![]),
            ("node", vec!["tools/srv.js"]),
        ] {
            assert!(runs_folder_file(&stdio(cmd, &args), dir), "{cmd} {args:?}");
        }
        for (cmd, args) in [("npx", vec!["-y", "@modelcontextprotocol/server-memory"]), ("uvx", vec!["mcp-server-time"]), ("node", vec![abs_out.to_str().unwrap()]), ("server.js", vec![])] {
            assert!(!runs_folder_file(&stdio(cmd, &args), dir), "{cmd} {args:?}");
        }
        let mut http = stdio("node", &["server.js"]);
        http.transport = "http".into();
        assert!(!runs_folder_file(&http, dir));
    }

    // The folder given through a symlink, and a server naming a file there that doesn't exist yet:
    // canonicalizing that path fails, so the typed folder is what catches it (also Windows' 8.3 names)
    #[cfg(unix)]
    #[test]
    fn a_file_named_through_the_typed_folder_path_is_spotted() {
        let t = tempfile::tempdir().unwrap();
        let real = t.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = t.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let later = link.join("tools/not-yet.js");
        assert!(runs_folder_file(&stdio("node", &[later.to_str().unwrap()]), &link));
        assert!(runs_folder_file(&stdio(later.to_str().unwrap(), &[]), &link));
        assert!(!runs_folder_file(&stdio("node", &[t.path().join("elsewhere.js").to_str().unwrap()]), &link));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 29o: a Deny's reason is one line, trimmed and at most 500 chars; nothing left is a plain Deny.
    #[test]
    fn a_deny_reason_is_one_trimmed_line_of_at_most_500_chars() {
        assert_eq!(deny_reason("  use the staging database  ").as_deref(), Some("use the staging database"));
        assert_eq!(deny_reason("push\nwithout\r\n--force\there\u{7}now").as_deref(), Some("push without --force here now"));
        assert_eq!(deny_reason("a  \n\n  b").as_deref(), Some("a b"));
        for empty in ["", "   ", "\n\t\r", "\u{0}"] {
            assert_eq!(deny_reason(empty), None, "{empty:?}");
        }
        let long = "é".repeat(501);
        assert_eq!(deny_reason(&long).map(|r| r.chars().count()), Some(DENY_REASON_MAX));
        assert_eq!(deny_reason(&"x".repeat(500)).map(|r| r.len()), Some(500));
        // Cut at 500, then trimmed: no trailing space
        let edge = format!("{} y", "x".repeat(499));
        assert_eq!(deny_reason(&edge), Some("x".repeat(499)));
    }

    /// 29o: a plain Deny is still told [`DENIED_TEXT`] word for word; a Deny with a reason hears it,
    /// and may try another way the person pointed to. Other refusals ignore a reason.
    #[test]
    fn a_deny_with_a_reason_tells_the_bot_why() {
        assert_eq!(ApprovalOutcome::Denied.refusal(None), DENIED_TEXT);
        assert_eq!(
            ApprovalOutcome::Denied.refusal(Some("use the staging database")),
            "The user denied this tool call. They said why: \"use the staging database\". Don't make this same call again. \
If what they said points to another way, you may try that; it will ask them again. Otherwise say in your reply what you couldn't do."
        );
        for other in [ApprovalOutcome::DeclinedBefore, ApprovalOutcome::Unanswered, ApprovalOutcome::Rehearsed] {
            assert_eq!(other.refusal(Some("why")), other.refusal_text(), "{other:?}");
        }
    }

    /// 29o round 2: a Deny with a reason, as the claude CLI reports it back (an error carrying the
    /// permission prompt's message), still ends the tool step `declined` in the person's words,
    /// paired with its card; the reason and the rest of the bot's text stay out of the step.
    /// 29s: the reason shows once, on the card's approval step, as the person's own words.
    #[test]
    fn a_deny_with_a_reason_still_ends_the_step_declined() {
        use crate::drivers::activity::ActivityLog;
        use crate::drivers::events::RuntimeEvent;
        let first = |t: &str| t.split_inclusive('.').next().unwrap_or(t).to_string();
        let said = ApprovalOutcome::Denied.refusal(Some("push without --force"));
        assert_eq!(first(&said), first(DENIED_TEXT), "same first sentence as DENIED_TEXT");
        for text in [with_no_false_claims(&said), said.clone()] {
            let mut log = ActivityLog::default();
            log.wait("approval", "t1", "Waiting for your approval: Running `git push --force`", Some("Bash"));
            log.settle_with("t1", "declined", Some("push without --force"));
            log.observe(&RuntimeEvent::ToolCallPending {
                id: "a".into(),
                name: "Bash".into(),
                args: serde_json::json!({"command": "git push --force"}),
            });
            let ended = log.observe(&RuntimeEvent::ToolCallCompleted {
                id: "a".into(),
                result: serde_json::json!({"status": "error", "error": text}),
            });
            assert_eq!(
                (ended[0].kind, ended[0].status, ended[0].detail.as_deref()),
                ("tool", "declined", Some(DENIED_STEP_DETAIL))
            );
            let details: Vec<_> = log.steps().iter().map(|s| (s.kind, s.status, s.detail.as_deref())).collect();
            assert_eq!(
                details,
                vec![
                    ("approval", "declined", Some("You said why: \u{201c}push without --force\u{201d}")),
                    ("tool", "declined", Some(DENIED_STEP_DETAIL)),
                ]
            );
            let shown = serde_json::to_string(log.steps()).unwrap();
            assert!(!shown.contains("They said why") && !shown.contains("Don't make this same call"), "{shown}");
        }
    }

    /// 29o: the reason reaches only the call that is listening, and only on a denial.
    #[tokio::test]
    async fn a_deny_reason_is_heard_only_by_its_own_call() {
        let denied = || async {
            assert!(tell_deny_reason("use staging".into()));
            ApprovalOutcome::Denied
        };
        assert_eq!(hear_deny_reason(denied()).await, (ApprovalOutcome::Denied, Some("use staging".into())));
        // Nobody listening: dropped
        assert!(!tell_deny_reason("lost".into()));
        // A reason left beside an outcome that isn't a denial is never heard
        let allowed = async {
            tell_deny_reason("why".into());
            ApprovalOutcome::Allowed
        };
        assert_eq!(hear_deny_reason(allowed).await, (ApprovalOutcome::Allowed, None));
        // A plain Deny has none
        assert_eq!(hear_deny_reason(async { ApprovalOutcome::Denied }).await, (ApprovalOutcome::Denied, None));
    }

    /// 27b: a first no tells the bot not to try another way; a call refused because of an earlier
    /// no says so, and is recorded as a denial (no extra reminder, nothing claimed done).
    #[test]
    fn a_no_tells_the_bot_not_to_try_another_way() {
        assert!(DENIED_TEXT.starts_with("The user denied this tool call. "));
        assert!(DENIED_TEXT.ends_with(NOT_ANOTHER_WAY_TEXT));
        assert_eq!(ApprovalOutcome::Denied.refusal_text(), DENIED_TEXT);
        assert_eq!(ApprovalOutcome::DeclinedBefore.refusal_text(), DECLINED_BEFORE_TEXT);
        assert_eq!(ApprovalOutcome::DeclinedBefore.record_status(), "denied");
        assert!(!ApprovalOutcome::DeclinedBefore.allowed());
        assert!(missed_status("denied") && !reminds("denied"));
    }

    fn input(json: Value) -> McpServerInput {
        serde_json::from_value(json).unwrap()
    }

    #[test]
    fn validates_names_and_transports() {
        assert!(build_server(input(serde_json::json!({"name": "ok-name_1", "transport": "stdio", "command": "x"})), None).is_ok());
        for bad in ["", "-lead", "a__b", "has space", "kwnt", "KWNT", &"x".repeat(49)] {
            assert!(build_server(input(serde_json::json!({"name": bad, "transport": "stdio", "command": "x"})), None).is_err(), "{bad}");
        }
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio"})), None).is_err());
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "http", "url": "ftp://x"})), None).is_err());
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "http", "url": "https://x.dev/mcp", "command": "y"})), None).is_err());
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "ws", "url": "https://x"})), None).is_err());
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio", "command": "x", "env": {"1BAD": "v"}})), None).is_err());
        assert!(build_server(input(serde_json::json!({"name": "a", "transport": "stdio", "command": "x", "timeout_secs": 0})), None).is_err());
    }

    #[test]
    fn masks_and_merges_secrets() {
        let created = build_server(
            input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"TOKEN": "s3cret", "OTHER": "o"}})),
            None,
        )
        .unwrap();
        let view = McpServerView::from(&created);
        assert_eq!(view.env.get("TOKEN").unwrap(), SECRET_MASK);
        assert!(!serde_json::to_string(&view).unwrap().contains("s3cret"));
        assert!(!format!("{created:?}").contains("s3cret"));

        // Mask keeps, new value replaces, omitted key deletes
        let updated = build_server(
            input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"TOKEN": SECRET_MASK, "NEW": "n"}})),
            Some(&created),
        )
        .unwrap();
        assert_eq!(updated.env.get("TOKEN").unwrap(), "s3cret");
        assert_eq!(updated.env.get("NEW").unwrap(), "n");
        assert!(!updated.env.contains_key("OTHER"));

        // Omitted map keeps everything
        let kept = build_server(input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x"})), Some(&created)).unwrap();
        assert_eq!(kept.env, created.env);

        // A mask for a key that was never stored is an error, not an empty secret
        assert!(build_server(
            input(serde_json::json!({"name": "gh", "transport": "stdio", "command": "x", "env": {"NOPE": SECRET_MASK}})),
            Some(&created)
        )
        .is_err());
    }

    #[test]
    fn redacts_and_splits_names() {
        assert_eq!(redact("token=abc123 and abc", &["abc123".into(), "".into()]), "token=******** and abc");
        assert_eq!(split_tool_name("mcp__gh__create_issue"), Some(("gh", "create_issue")));
        assert_eq!(split_tool_name("mcp__gh__a__b"), Some(("gh", "a__b")));
        assert_eq!(split_tool_name("Bash"), None);
        assert_eq!(namespaced_tool_name("gh", "x"), "mcp__gh__x");
        assert_eq!(truncate_text("héllo", 2), "hé… [truncated]");
    }

    /// 26b: the reminder goes with a failed or unanswered result, never a plain denial (the bot
    /// is told it was denied) or a call that ran or was a dry run. `had_miss` reads the same rule,
    /// so a denial alone doesn't use up the turn's one reminder.
    #[test]
    fn the_reminder_goes_with_failed_or_unanswered_calls_only() {
        for status in ["error", "failed", "cancelled", "unanswered"] {
            assert!(reminds(status), "{status}");
        }
        for status in ["denied", "ok", "rehearsed", "allowed", ""] {
            assert!(!reminds(status), "{status}");
        }
        assert!(missed_status("denied"), "a denial still didn't run");
    }
}