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.

gateway: grok naming mode with names grok accepts

Lin (kwant bot)2914be32f365
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 00a8a77d..271a948b 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -372,7 +372,7 @@ impl CliDriver {
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);
+ super::grok::add_gateway(&mut config, &gateway.grok_url(), slowest);
args.push("--allow".into());
args.push(super::grok::gateway_allow_rule());
}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 492e80e1..8a6f8150 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -294,6 +294,13 @@ pub struct GatewayAccess {
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()
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index ff8d3136..f95c0a39 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -18,6 +18,50 @@ struct OfferedTool {
name: String,
server_index: usize,
tool: McpTool,
+ /// The name grok sees (see [`grok_tool_names`]).
+ grok_name: String,
+}
+
+/// How kwnt's gateway names the tools it offers an agent CLI.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GatewayNaming {
+ /// `<server>__<tool>` (codex).
+ Plain,
+ /// `<server>-<tool>` with no `__` (grok rejects `__` inside an MCP tool name).
+ Grok,
+}
+
+/// grok's name for `<server>`'s `<tool>`: `<server>-<tool>`, every character outside
+/// `[A-Za-z0-9_-]` replaced by `_` and runs of `_` collapsed, so there is never a `__`.
+fn grok_base_name(server: &str, tool: &str) -> String {
+ let mut name = String::with_capacity(server.len() + tool.len() + 1);
+ for c in format!("{server}-{tool}").chars() {
+ let c = if c.is_ascii_alphanumeric() || c == '-' { c } else { '_' };
+ if !(c == '_' && name.ends_with('_')) {
+ name.push(c);
+ }
+ }
+ name
+}
+
+/// grok names for `(server, tool)` pairs, in order. Distinct tools whose names map to the same
+/// grok name get a `-2`, `-3`, … suffix (first one keeps the plain name), never reusing a name
+/// another tool maps to plainly, so every grok name stands for exactly one tool.
+pub fn grok_tool_names(tools: &[(&str, &str)]) -> Vec<String> {
+ let bases: Vec<String> = tools.iter().map(|(server, tool)| grok_base_name(server, tool)).collect();
+ let mut taken: std::collections::HashSet<String> = bases.iter().cloned().collect();
+ let mut seen = std::collections::HashSet::new();
+ bases
+ .into_iter()
+ .map(|base| {
+ if seen.insert(base.clone()) {
+ return base;
+ }
+ let name = (2..).map(|n| format!("{base}-{n}")).find(|candidate| !taken.contains(candidate)).unwrap();
+ taken.insert(name.clone());
+ name
+ })
+ .collect()
}
/// Who is asking, for approval cards.
@@ -69,7 +113,7 @@ impl McpToolSession {
for tool in tools {
let name = namespaced_tool_name(&server.name, &tool.name);
if valid_function_name(&name) {
- session.tools.push(OfferedTool { name, server_index: index, tool });
+ session.tools.push(OfferedTool { name, server_index: index, tool, grok_name: String::new() });
} else {
tracing::warn!(server = %server.name, tool = %tool.name, "MCP tool name not usable as a function name; skipped");
}
@@ -79,6 +123,12 @@ impl McpToolSession {
Err(e) => problems.push(format!("{}: {}", server.name, redact(&e.to_string(), &session.secrets))),
}
}
+ let pairs: Vec<(&str, &str)> =
+ session.tools.iter().map(|t| (session.clients[t.server_index].0.as_str(), t.tool.name.as_str())).collect();
+ let grok_names = grok_tool_names(&pairs);
+ for (tool, grok_name) in session.tools.iter_mut().zip(grok_names) {
+ tool.grok_name = grok_name;
+ }
(session, problems)
}
@@ -103,9 +153,10 @@ impl McpToolSession {
.collect()
}
- /// The `tools/list` result for kwnt's MCP gateway. Tools are named `<server>__<tool>`, so an
- /// agent CLI that prefixes `mcp__kwnt__` still shows which server a tool belongs to.
- pub fn gateway_tools(&self) -> Vec<Value> {
+ /// The `tools/list` result for kwnt's MCP gateway. Tools are named `<server>__<tool>` (or
+ /// grok's `<server>-<tool>`), so an agent CLI that prefixes its own server name still shows
+ /// which server a tool belongs to.
+ pub fn gateway_tools(&self, naming: GatewayNaming) -> Vec<Value> {
self.tools
.iter()
.map(|t| {
@@ -113,8 +164,12 @@ impl McpToolSession {
if !schema.is_object() {
schema = json!({"type": "object", "properties": {}});
}
+ let name = match naming {
+ GatewayNaming::Plain => t.name.strip_prefix("mcp__").unwrap_or(&t.name),
+ GatewayNaming::Grok => &t.grok_name,
+ };
json!({
- "name": t.name.strip_prefix("mcp__").unwrap_or(&t.name),
+ "name": name,
"description": t.tool.description.clone().unwrap_or_default(),
"inputSchema": schema,
})
@@ -122,6 +177,15 @@ impl McpToolSession {
.collect()
}
+ /// The `mcp__<server>__<tool>` name a gateway tool name stands for; the approval card and
+ /// the call record use it. `None` for a grok name the gateway never offered.
+ pub fn canonical_name(&self, naming: GatewayNaming, gateway_name: &str) -> Option<String> {
+ match naming {
+ GatewayNaming::Plain => Some(format!("mcp__{gateway_name}")),
+ GatewayNaming::Grok => self.tools.iter().find(|t| t.grok_name == gateway_name).map(|t| t.name.clone()),
+ }
+ }
+
/// Runs one model-requested call: approval first, then the MCP call. The record is also
/// appended to the turn's `tool_calls`.
pub async fn call(&self, caller: &Caller, call_id: &str, name: &str, raw_arguments: &str) -> CallOutcome {
@@ -188,3 +252,31 @@ impl McpToolSession {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn grok_names_have_no_double_underscore() {
+ let names = grok_tool_names(&[("alpha", "alpha_ping"), ("gh", "create__issue"), ("a-b", "x__y___z_")]);
+ assert_eq!(names, ["alpha-alpha_ping", "gh-create_issue", "a-b-x_y_z_"]);
+ assert!(names.iter().all(|n| !n.contains("__")));
+ }
+
+ #[test]
+ fn grok_name_collisions_get_unique_suffixes() {
+ let names = grok_tool_names(&[
+ ("a", "b-c"),
+ ("a-b", "c"), // same base as the first
+ ("gh", "x__y"), // `gh-x_y`
+ ("gh", "x_y"), // same base
+ ("gh", "x_y-2"), // the suffix the previous one would naively get
+ ("a", "b-c"), // a third `a-b-c`
+ ]);
+ assert_eq!(names, ["a-b-c", "a-b-c-2", "gh-x_y", "gh-x_y-3", "gh-x_y-2", "a-b-c-3"]);
+ let unique: std::collections::HashSet<_> = names.iter().collect();
+ assert_eq!(unique.len(), names.len());
+ assert!(names.iter().all(|n| !n.contains("__")));
+ }
+}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 2f3c2ae8..cf0803ae 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -11,7 +11,7 @@ use crate::drivers::events::RuntimeEvent;
use crate::mcp::{
self,
client::PROTOCOL_VERSION,
- session::{Caller, McpToolSession},
+ session::{Caller, GatewayNaming, McpToolSession},
GatewayAccess, McpTurnContext, ToolApprovalRequest, ToolApprover,
};
use async_trait::async_trait;
@@ -388,7 +388,17 @@ fn bearer_token(headers: &HeaderMap) -> Option<&str> {
/// stays out of URLs and argv. Every call is approved through the turn's approver (the
/// approval card) before it is forwarded, and recorded like any other MCP call.
pub async fn gateway_endpoint(State(state): State<AppState>, headers: HeaderMap, Json(msg): Json<Value>) -> Response {
- let session = match bearer_token(&headers) {
+ gateway_rpc(&state, &headers, msg, GatewayNaming::Plain).await
+}
+
+/// `POST /api/mcp/gateway/grok`: the same gateway, with tool names grok accepts (no `__`).
+/// Calls are mapped back to the real tool, so approval cards and records show its usual name.
+pub async fn gateway_grok_endpoint(State(state): State<AppState>, headers: HeaderMap, Json(msg): Json<Value>) -> Response {
+ gateway_rpc(&state, &headers, msg, GatewayNaming::Grok).await
+}
+
+async fn gateway_rpc(state: &AppState, headers: &HeaderMap, msg: Value, naming: GatewayNaming) -> Response {
+ let session = match bearer_token(headers) {
Some(token) => state.mcp_sessions.lock().await.get(token).cloned(),
None => None,
};
@@ -409,7 +419,7 @@ pub async fn gateway_endpoint(State(state): State<AppState>, headers: HeaderMap,
),
"ping" => rpc_result(id, json!({})),
"tools/list" => match session.tool_session().await {
- Some(tools) => rpc_result(id, json!({"tools": tools.gateway_tools()})),
+ Some(tools) => rpc_result(id, json!({"tools": tools.gateway_tools(naming)})),
None => StatusCode::UNAUTHORIZED.into_response(),
},
"tools/call" => {
@@ -421,7 +431,8 @@ pub async fn gateway_endpoint(State(state): State<AppState>, headers: HeaderMap,
let Some(tools) = session.tool_session().await else {
return StatusCode::UNAUTHORIZED.into_response();
};
- let tool_name = format!("mcp__{name}");
+ // An unknown grok name stays as given, and the call fails as an unknown tool
+ let tool_name = tools.canonical_name(naming, name).unwrap_or_else(|| name.to_string());
// Dropping the call withdraws its card (or stops the forwarded call) when the turn ends
let (caller, raw_arguments) = (session.caller(), arguments.to_string());
let outcome = tokio::select! {
diff --git a/src/server/mod.rs b/src/server/mod.rs
index c69be68b..8beb1f29 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -118,6 +118,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/kwants/:id/mcp-servers", get(mcp_routes::get_kwant_servers).put(mcp_routes::set_kwant_servers))
.route("/api/mcp/permission/:token", post(mcp_runtime::permission_endpoint))
.route("/api/mcp/gateway", post(mcp_runtime::gateway_endpoint))
+ .route("/api/mcp/gateway/grok", post(mcp_runtime::gateway_grok_endpoint))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(cors)
diff --git a/tests/grok_driver_test.rs b/tests/grok_driver_test.rs
index ed231a34..129620e6 100644
--- a/tests/grok_driver_test.rs
+++ b/tests/grok_driver_test.rs
@@ -323,6 +323,11 @@ async fn grok_gets_the_gateway_with_the_token_in_env_only() {
);
let config: toml::Table = config_text.parse().unwrap();
let servers = config["mcp_servers"].as_table().unwrap();
+ assert_eq!(
+ servers["kwnt"]["url"].as_str(),
+ Some("http://127.0.0.1:1/api/mcp/gateway/grok"),
+ "grok naming mode"
+ );
assert_eq!(
servers.keys().collect::<Vec<_>>(),
["kwnt"],
diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rs
index 90789117..96c0ae4b 100644
--- a/tests/mcp_gateway_test.rs
+++ b/tests/mcp_gateway_test.rs
@@ -299,3 +299,54 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {
assert_eq!(records[0]["status"], "cancelled");
assert!(records[0].get("result").is_none());
}
+
+/// Approves everything and remembers what each approval card would have shown.
+struct RecordingApprover(std::sync::Mutex<Vec<kwnt::mcp::ToolApprovalRequest>>);
+
+#[async_trait::async_trait]
+impl ToolApprover for RecordingApprover {
+ async fn approve(&self, request: kwnt::mcp::ToolApprovalRequest) -> bool {
+ self.0.lock().unwrap().push(request);
+ true
+ }
+}
+
+#[tokio::test]
+async fn grok_gateway_names_have_no_double_underscore_and_map_back() {
+ let (state, _tmp) = state().await;
+ let base = serve(state.clone()).await;
+ let approver = Arc::new(RecordingApprover(Default::default()));
+ let ctx = register(&state, "grok-tok", approver.clone()).await;
+
+ let mut grok_gateway = gateway(&base, Some("grok-tok"));
+ grok_gateway.url = Some(format!("{base}/api/mcp/gateway/grok"));
+ let mut client = McpClient::connect(&grok_gateway, None).await.unwrap();
+ let tools = client.list_tools().await.unwrap();
+ let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
+ assert!(names.contains(&"echo-echo") && names.contains(&"echo-add"), "{names:?}");
+ assert!(names.iter().all(|n| !n.contains("__")), "{names:?}");
+
+ let out = client.call_tool("echo-echo", json!({"text": "hello grok"})).await.unwrap();
+ assert!(!out.is_error);
+ assert_eq!(out.text, "hello grok");
+ // The plain gateway names aren't valid in grok mode
+ let plain = client.call_tool("echo__echo", json!({"text": "x"})).await.unwrap();
+ assert!(plain.is_error, "{}", plain.text);
+ client.shutdown().await;
+
+ // The approval card and the record show the real tool name
+ let cards = approver.0.lock().unwrap().clone();
+ assert_eq!(cards.len(), 1);
+ assert_eq!(cards[0].tool_name, "mcp__echo__echo");
+ assert_eq!((cards[0].server.as_str(), cards[0].tool.as_str()), ("echo", "echo"));
+ let records = ctx.take_records();
+ assert_eq!(records[0]["name"], "mcp__echo__echo");
+ assert_eq!(records[0]["status"], "ok");
+
+ // The plain gateway is unchanged for codex on the same turn
+ let mut codex = McpClient::connect(&gateway(&base, Some("grok-tok")), None).await.unwrap();
+ let codex_names: Vec<_> = codex.list_tools().await.unwrap().into_iter().map(|t| t.name).collect();
+ assert!(codex_names.contains(&"echo__echo".to_string()), "{codex_names:?}");
+ codex.shutdown().await;
+ mcp_runtime::finish_turn(&state, "grok-tok").await;
+}