Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
grok: offer the kwant's MCP tools through kwnt's gateway
Lin (kwant bot)1b7d6657d07d
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex d6fda5a7..00a8a77d 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -225,12 +225,18 @@ struct GrokLaunch<'a> {config: toml::Table,/// The user's grok login file, if they have one.auth_file: Option<std::path::PathBuf>,+ /// This turn's gateway token, handed over in grok's env only.+ gateway_token: Option<String>,}/// What one grok process left behind.struct GrokRun {+ /// The reply text from grok's `text` events.stdout: String,stderr: String,+ /// grok's `error` events.+ errors: Vec<String>,+ stop_reason: Option<String>,}/// Reads a pipe to the end, keeping at most the last `max` bytes.@@ -277,6 +283,11 @@ impl CliDriver {}(None, _) => {}}+ // Never written to disk: the config's header refers to this variable by name+ match &launch.gateway_token {+ Some(token) => cmd.env(crate::mcp::GATEWAY_TOKEN_ENV, token),+ None => cmd.env_remove(crate::mcp::GATEWAY_TOKEN_ENV),+ };cmd.args(&launch.args);cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());// A cancelled turn aborts this task; the CLI must not outlive it@@ -286,19 +297,35 @@ impl CliDriver {let stdout_pipe = child.stdout.take();let stderr_pipe = child.stderr.take();let read_stdout = async {- let mut text = String::new();- let mut buffer = [0u8; 1024];+ let mut run = GrokRun { stdout: String::new(), stderr: String::new(), errors: Vec::new(), stop_reason: None };+ let mut parser = super::grok::StreamParser::default();+ let mut buffer = [0u8; 4096];+ // Bytes of a UTF-8 character split across reads+ let mut partial: Vec<u8> = Vec::new();if let Some(mut stdout) = stdout_pipe {- while let Ok(n) = stdout.read(&mut buffer).await {- if n == 0 {- break;+ loop {+ let n = match stdout.read(&mut buffer).await {+ Ok(0) | Err(_) => break,+ Ok(n) => n,+ };+ partial.extend_from_slice(&buffer[..n]);+ let valid = match std::str::from_utf8(&partial) {+ Ok(_) => partial.len(),+ Err(e) if e.error_len().is_none() => e.valid_up_to(),+ Err(_) => partial.len(),+ };+ let chunk = String::from_utf8_lossy(&partial[..valid]).into_owned();+ partial.drain(..valid);+ for event in parser.push(&chunk) {+ Self::apply_grok_event(event, &mut run, event_tx).await;}- let chunk = String::from_utf8_lossy(&buffer[..n]).to_string();- let _ = event_tx.send(RuntimeEvent::TextDelta(chunk.clone())).await;- text.push_str(&chunk);}}- text+ let rest = String::from_utf8_lossy(&partial).into_owned();+ for event in parser.push(&rest).into_iter().chain(parser.finish()) {+ Self::apply_grok_event(event, &mut run, event_tx).await;+ }+ run};let read_stderr = async {match stderr_pipe {@@ -306,21 +333,33 @@ impl CliDriver {None => String::new(),}};- let (stdout, stderr) = tokio::join!(read_stdout, read_stderr);+ let (mut run, stderr) = tokio::join!(read_stdout, read_stderr);let _ = child.wait().await;drop(home);- Ok(GrokRun { stdout, stderr })+ run.stderr = stderr;+ Ok(run)+ }++ async fn apply_grok_event(event: super::grok::StreamEvent, run: &mut GrokRun, event_tx: &mpsc::Sender<RuntimeEvent>) {+ match event {+ super::grok::StreamEvent::Text(text) => {+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;+ run.stdout.push_str(&text);+ }+ super::grok::StreamEvent::Error(message) => run.errors.push(message),+ super::grok::StreamEvent::End { stop_reason } => run.stop_reason = stop_reason,+ }}async fn run_grok(&self,bin_path: &str,input: &TurnInput,- args: Vec<String>,+ mut args: Vec<String>,event_tx: &mpsc::Sender<RuntimeEvent>,) -> std::io::Result<GrokRun> {let user_home = self.grok_home.clone().or_else(super::grok::user_grok_home);- let config = user_home+ let mut config = user_home.as_ref().and_then(|h| std::fs::read_to_string(h.join("config.toml")).ok()).map(|text| super::grok::model_settings(&text))@@ -330,7 +369,17 @@ impl CliDriver {.map(std::path::PathBuf::from).or_else(|| user_home.map(|h| h.join("auth.json"))).filter(|p| p.is_file());- let launch = GrokLaunch { bin_path, input, args, config, auth_file };+ let gateway = input.mcp.as_ref().and_then(|c| c.gateway.as_ref().map(|g| (c, g)));+ if let Some((ctx, gateway)) = gateway {+ let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);+ super::grok::add_gateway(&mut config, &gateway.url, slowest);+ args.push("--allow".into());+ args.push(super::grok::gateway_allow_rule());+ }+ args.push("--output-format".into());+ args.push("streaming-json".into());+ let gateway_token = gateway.map(|(_, g)| g.token.clone());+ let launch = GrokLaunch { bin_path, input, args, config, auth_file, gateway_token };let run = Self::run_grok_once(&launch, GrokAuth::InPlace, event_tx).await?;if launch.auth_file.is_some() && run.stdout.trim().is_empty() && super::grok::not_signed_in(&run.stderr) {// Nothing ran: grok stops before the model when it finds no login@@ -397,15 +446,6 @@ impl Driver for CliDriver {cmd.env("BROWSER", "none");cmd.env("DISPLAY", "");- 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.",- self.tool_kind- )))- .await;- }-match self.tool_kind.as_str() {"codex" => {let out_file = format!("/tmp/kwnt_codex_{}.txt", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos());diff --git a/src/drivers/grok.rs b/src/drivers/grok.rsindex 5c60e644..be2a27b3 100644--- a/src/drivers/grok.rs+++ b/src/drivers/grok.rs@@ -136,6 +136,101 @@ pub fn not_signed_in(stderr: &str) -> bool {stderr.contains("Not signed in")}+/// Adds kwnt's gateway as the run's only MCP server. The token is not written: grok expands+/// `${VAR}` in headers from its own env, and the shell policy hides that variable from the+/// commands grok runs. `slowest` is the longest timeout among the kwant's servers.+pub fn add_gateway(config: &mut toml::Table, url: &str, slowest: u64) {+ let token_env = crate::mcp::GATEWAY_TOKEN_ENV;+ // The gateway connects to every server on grok's first tools/list+ let startup_secs = (slowest + 15).max(30);+ // A call may wait for the user's approval; grok must not give up first+ let tool_secs = (crate::mcp::APPROVAL_TIMEOUT_SECS + 30).max(slowest);+ let mut headers = toml::Table::new();+ headers.insert(+ "Authorization".into(),+ format!("Bearer ${{{token_env}}}").into(),+ );+ let mut server = toml::Table::new();+ server.insert("url".into(), url.into());+ server.insert("headers".into(), headers.into());+ server.insert("startup_timeout_sec".into(), (startup_secs as i64).into());+ server.insert("tool_timeout_sec".into(), (tool_secs as i64).into());+ let mut servers = toml::Table::new();+ servers.insert(crate::mcp::RESERVED_SERVER_NAME.into(), server.into());+ config.insert("mcp_servers".into(), servers.into());+ let mut policy = toml::Table::new();+ policy.insert("exclude".into(), toml::Value::Array(vec![token_env.into()]));+ config.insert("shell_environment_policy".into(), policy.into());+}++/// The `--allow` rule that lets grok call the gateway's tools without its own (headless,+/// always-refused) approval prompt. kwnt's approval card is shown by the gateway instead.+pub fn gateway_allow_rule() -> String {+ format!("MCPTool({}__*)", crate::mcp::RESERVED_SERVER_NAME)+}++/// One event of grok's `--output-format streaming-json` that kwnt acts on.+#[derive(Debug, Clone, PartialEq)]+pub enum StreamEvent {+ /// A chunk of the reply.+ Text(String),+ /// grok reported an error.+ Error(String),+ /// The run ended; `stop_reason` is e.g. `end_turn`, `refusal`, `cancelled`.+ End { stop_reason: Option<String> },+}++/// Splits grok's NDJSON output into events. Lines that aren't JSON are passed on as text, so+/// a grok that ignores `--output-format` still gets its reply through.+#[derive(Debug, Default)]+pub struct StreamParser {+ pending: String,+}++impl StreamParser {+ pub fn push(&mut self, chunk: &str) -> Vec<StreamEvent> {+ self.pending.push_str(chunk);+ let mut events = Vec::new();+ while let Some(end) = self.pending.find('\n') {+ let line: String = self.pending.drain(..=end).collect();+ events.extend(parse_line(&line));+ }+ events+ }++ /// Whatever is left after the last newline.+ pub fn finish(&mut self) -> Vec<StreamEvent> {+ let rest = std::mem::take(&mut self.pending);+ parse_line(&rest).into_iter().collect()+ }+}++fn parse_line(line: &str) -> Option<StreamEvent> {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ return None;+ }+ let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) else {+ return Some(StreamEvent::Text(line.to_string()));+ };+ match value["type"].as_str() {+ Some("text") => value["data"]+ .as_str()+ .map(|t| StreamEvent::Text(t.to_string())),+ Some("error") => Some(StreamEvent::Error(+ value["message"]+ .as_str()+ .unwrap_or("unknown error")+ .to_string(),+ )),+ Some("end") => Some(StreamEvent::End {+ stop_reason: value["stopReason"].as_str().map(str::to_string),+ }),+ Some(_) => None,+ None => Some(StreamEvent::Text(line.to_string())),+ }+}+#[cfg(test)]mod tests {use super::*;@@ -162,6 +257,88 @@ enabled = trueallow = ["Bash(*)"]"#;+ #[test]+ fn gateway_config_keeps_the_token_out_of_the_file() {+ let mut config = model_settings(USER_CONFIG);+ add_gateway(&mut config, "http://127.0.0.1:7/api/mcp/gateway/grok", 400);+ let text = toml::to_string(&config).unwrap();+ let parsed: toml::Table = text.parse().unwrap();+ let kwnt = &parsed["mcp_servers"]["kwnt"];+ assert_eq!(+ parsed["mcp_servers"].as_table().unwrap().len(),+ 1,+ "only the gateway: {text}"+ );+ assert_eq!(+ kwnt["url"].as_str(),+ Some("http://127.0.0.1:7/api/mcp/gateway/grok")+ );+ assert_eq!(+ kwnt["headers"]["Authorization"].as_str(),+ Some("Bearer ${KWNT_MCP_GATEWAY_TOKEN}")+ );+ assert_eq!(kwnt["startup_timeout_sec"].as_integer(), Some(415));+ assert_eq!(kwnt["tool_timeout_sec"].as_integer(), Some(400));+ assert_eq!(+ parsed["shell_environment_policy"]["exclude"]+ .as_array()+ .unwrap(),+ &vec![toml::Value::from("KWNT_MCP_GATEWAY_TOKEN")]+ );+ assert_eq!(parsed["models"]["default"].as_str(), Some("mock"));++ // Short server timeouts still leave room for the approval wait+ let mut config = toml::Table::new();+ add_gateway(&mut config, "http://x", 0);+ assert_eq!(+ config["mcp_servers"]["kwnt"]["startup_timeout_sec"].as_integer(),+ Some(30)+ );+ assert_eq!(+ config["mcp_servers"]["kwnt"]["tool_timeout_sec"].as_integer(),+ Some(330)+ );+ assert_eq!(gateway_allow_rule(), "MCPTool(kwnt__*)");+ }++ #[test]+ fn written_gateway_home_never_contains_the_token() {+ let base = tempfile::tempdir().unwrap();+ let mut config = model_settings(USER_CONFIG);+ add_gateway(&mut config, "http://127.0.0.1:7/api/mcp/gateway/grok", 30);+ let home = GrokHome::create(base.path(), &config).unwrap();+ let written = std::fs::read_to_string(home.path.join("config.toml")).unwrap();+ assert!(written.contains("${KWNT_MCP_GATEWAY_TOKEN}"), "{written}");+ assert!(!written.contains("grokuser"));+ for entry in std::fs::read_dir(&home.path).unwrap() {+ assert_eq!(entry.unwrap().file_name(), "config.toml");+ }+ }++ #[test]+ fn parses_streaming_json_across_chunks() {+ let mut parser = StreamParser::default();+ let mut events =+ parser.push("{\"type\":\"available_commands\",\"tools\":[]}\n{\"type\":\"text\",\"da");+ events.extend(parser.push("ta\":\"Hel\"}\n{\"type\":\"text\",\"data\":\"lo\\n\"}\n"));+ events.extend(parser.push("{\"type\":\"tool_call\",\"toolCallId\":\"c1\"}\nplain line\n"));+ events.extend(parser.push("{\"type\":\"error\",\"message\":\"boom\"}\n{\"type\":\"end\",\"stopReason\":\"end_turn\"}"));+ events.extend(parser.finish());+ assert_eq!(+ events,+ [+ StreamEvent::Text("Hel".into()),+ StreamEvent::Text("lo\n".into()),+ StreamEvent::Text("plain line\n".into()),+ StreamEvent::Error("boom".into()),+ StreamEvent::End {+ stop_reason: Some("end_turn".into())+ },+ ]+ );+ assert!(parser.finish().is_empty());+ }+#[test]fn keeps_only_model_settings() {let kept = model_settings(USER_CONFIG);diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rsindex 2674a816..ed231a34 100644--- a/tests/grok_driver_test.rs+++ b/tests/grok_driver_test.rs@@ -4,10 +4,13 @@use kwnt::{db::models::Kwant,+ db::models::McpServer,drivers::{events::RuntimeEvent, CliDriver, Driver, TurnInput},- mcp::McpTurnContext,+ mcp::{FixedApprover, GatewayAccess, McpTurnContext},};+use std::collections::BTreeMap;use std::path::{Path, PathBuf};+use std::sync::Arc;use tempfile::{tempdir, TempDir};const USER_CONFIG: &str = r#"@@ -274,3 +277,91 @@ async fn grok_killed_mid_run_still_removes_its_home() {assert_eq!(homes.len(), 1);assert!(!homes[0].exists());}++fn mcp_ctx(dir: &Path) -> McpTurnContext {+ let server = McpServer {+ id: "id-echo".into(),+ name: "echo".into(),+ transport: "stdio".into(),+ command: Some("/usr/bin/true".into()),+ args: vec![],+ url: None,+ env: BTreeMap::from([("API_TOKEN".to_string(), "sk-very-secret".to_string())]),+ headers: BTreeMap::new(),+ enabled: true,+ timeout_secs: 30,+ created_at: None,+ };+ McpTurnContext {+ servers: vec![server],+ approver: Arc::new(FixedApprover(true)),+ config_dir: dir.join("mcp"),+ permission_url: None,+ 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(),+ }+}++#[tokio::test]+async fn grok_gets_the_gateway_with_the_token_in_env_only() {+ let grok = FakeGrok::new("echo ok");+ grok.run(Some(mcp_ctx(grok.dir.path()))).await;+ let argv = grok.out("argv");+ let config_text = grok.out("config.toml");+ let env = grok.out("env");+ assert!(+ argv.contains("--allow\nMCPTool(kwnt__*)\n--output-format\nstreaming-json\n"),+ "{argv}"+ );+ assert_eq!(+ env_value(&env, "KWNT_MCP_GATEWAY_TOKEN").as_deref(),+ Some("gw-secret-token")+ );+ let config: toml::Table = config_text.parse().unwrap();+ let servers = config["mcp_servers"].as_table().unwrap();+ assert_eq!(+ servers.keys().collect::<Vec<_>>(),+ ["kwnt"],+ "only kwnt's gateway"+ );+ assert_eq!(+ servers["kwnt"]["headers"]["Authorization"].as_str(),+ Some("Bearer ${KWNT_MCP_GATEWAY_TOKEN}")+ );+ assert_eq!(+ config["shell_environment_policy"]["exclude"][0].as_str(),+ Some("KWNT_MCP_GATEWAY_TOKEN")+ );+ for secret in ["gw-secret-token", "sk-very-secret", "/usr/bin/true"] {+ assert!(!argv.contains(secret), "{secret} in argv: {argv}");+ assert!(+ !config_text.contains(secret),+ "{secret} in config: {config_text}"+ );+ }+ assert!(!grok.homes()[0].exists());+}++#[tokio::test]+async fn grok_without_tools_gets_no_gateway() {+ let grok = FakeGrok::new("echo ok");+ grok.run(None).await;+ let argv = grok.out("argv");+ assert!(!argv.contains("--allow"), "{argv}");+ assert!(argv.contains("--output-format\nstreaming-json\n"), "{argv}");+ assert_eq!(env_value(&grok.out("env"), "KWNT_MCP_GATEWAY_TOKEN"), None);+ assert!(!grok.out("config.toml").contains("mcp_servers"));+}++#[tokio::test]+async fn grok_reply_comes_from_streaming_json_text_events() {+ let grok = FakeGrok::new(+ r#"printf '%s\n' '{"type":"available_commands","tools":[]}' '{"type":"text","data":"Hel"}' '{"type":"tool_call","toolCallId":"c1"}' '{"type":"text","data":"lo ✓"}' '{"type":"end","stopReason":"end_turn"}'"#,+ );+ let (reply, _) = grok.run(None).await;+ assert_eq!(reply, "Hello ✓");+}diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 6c60b995..95e48b13 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -450,12 +450,15 @@ async fn codex_cli_does_not_run_when_its_servers_cannot_be_listed() {#[cfg(target_os = "linux")]#[tokio::test]-async fn grok_cli_still_runs_without_mcp() {+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, "unset");- assert!(!argv.contains("gateway"), "{argv}");- assert!(notes.iter().any(|n| n.contains("can't offer MCP tools through the grok CLI")), "{notes:?}");+ assert_eq!(token, "gw-secret-token", "token comes through the env");+ assert!(argv.contains("--allow MCPTool(kwnt__*) --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}");+ }+ assert!(!notes.iter().any(|n| n.contains("can't offer MCP tools")), "{notes:?}");}/// A cancelled turn aborts its driver task; the agent CLI must die with it rather than keep