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
Codex MCP: switch off or refuse a user codex server named kwnt
Lin (kwant bot)4899a16cf8f9
diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex 39d3329e..7de60eba 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -162,7 +162,10 @@ Body: `{"server_ids": ["…"]}` (replaces the whole assignment; `[]` clears it).which servers it would load for the turn (`codex mcp list --json`, run in the turn's workingdirectory: user config, profile, trusted-project `.codex/config.toml`, system config) and adds`"<name>"={enabled=false}` for each one into the same table, so they are neither offered nor- started. If that listing fails, kwnt doesn't run codex for the turn. The turn's token is passed+ started. If that listing fails, kwnt doesn't run codex for the turn. `kwnt` is reserved here+ too: a user codex server named `kwnt` is switched off like the others on turns without the+ gateway, but on a gateway turn the two entries would merge, so kwnt refuses the turn and asks+ the user to rename that server. The turn's token is passedin the `KWNT_MCP_GATEWAY_TOKEN` env variable and sent as `Authorization: Bearer`, never on thecommand line, and blanked for codex's own shell commands(`-c shell_environment_policy.set.KWNT_MCP_GATEWAY_TOKEN=""`); other tokens and finished turnsdiff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 7b34b998..ed9ed323 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -79,10 +79,14 @@ fn toml_string(value: &str) -> String {/// table is merged into codex's config, not swapped in, so the user's servers must be switched/// off by name; the names go inside the value because codex's `-c` key path can't quote. The/// gateway asks the user before every call, so codex's own approval is turned off for it; its-/// token is read from an env variable so it never appears in argv.+/// token is read from an env variable so it never appears in argv. A user server named like the+/// gateway is switched off like any other when there is no gateway; with one, the turn must be+/// refused first (see `codex_reserved_name_conflict`), since the two entries would merge.pub fn codex_mcp_servers(ctx: Option<&crate::mcp::McpTurnContext>, user_servers: &[String]) -> String {let mut entries = Vec::new();- if let Some((ctx, gateway)) = ctx.and_then(|c| c.gateway.as_ref().map(|g| (c, g))) {+ let gateway = ctx.and_then(|c| c.gateway.as_ref().map(|g| (c, g)));+ let has_gateway = gateway.is_some();+ if let Some((ctx, gateway)) = gateway {let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);// The gateway connects to every server on codex's first tools/listlet startup_secs = (slowest + 15).max(30);@@ -98,13 +102,24 @@ pub fn codex_mcp_servers(ctx: Option<&crate::mcp::McpTurnContext>, user_servers:));}for name in user_servers {- if name != crate::mcp::RESERVED_SERVER_NAME {+ if !(has_gateway && name == crate::mcp::RESERVED_SERVER_NAME) {entries.push(format!("{}={{enabled=false}}", toml_string(name)));}}format!("mcp_servers={{{}}}", entries.join(","))}+/// The message refusing a gateway turn when the user's codex config has its own server named+/// like kwnt's gateway: `-c` would merge the two entries rather than replace the user's.+pub fn codex_reserved_name_conflict(ctx: Option<&crate::mcp::McpTurnContext>, user_servers: &[String]) -> Option<String> {+ let reserved = crate::mcp::RESERVED_SERVER_NAME;+ (ctx.is_some_and(|c| c.gateway.is_some()) && user_servers.iter().any(|n| n == reserved)).then(|| {+ format!(+ "Your codex config has an MCP server named `{reserved}`, which kwnt reserves for its own tools, so it didn't run codex. Rename that server to use MCP tools in kwnt."+ )+ })+}+/// How long `codex mcp list` may take before the turn is refused.const CODEX_MCP_LIST_TIMEOUT: Duration = Duration::from_secs(15);@@ -255,15 +270,22 @@ impl Driver for CliDriver {};let full_prompt = format!("[System Context: {}]\n\n{}", system_prompt, effective_prompt);// Fail closed: without the names, the user's own servers would run with no- // approval card (and despite a per-kwant opt-out).- let user_servers = match codex_user_mcp_servers(&bin_path, input.workspace_dir.as_deref()).await {+ // approval card (and despite a per-kwant opt-out). Same for a user server named+ // like the gateway, which can't be switched off while the gateway uses its name.+ let listed = codex_user_mcp_servers(&bin_path, input.workspace_dir.as_deref()).await.map_err(|e| {+ tracing::warn!(error = %e, "could not list codex's own MCP servers; not running codex");+ format!(+ "kwnt couldn't check which MCP servers your codex config would start ({e}), so it didn't run codex. Check that `codex mcp list` works."+ )+ });+ let checked = listed.and_then(|names| match codex_reserved_name_conflict(input.mcp.as_ref(), &names) {+ Some(reason) => Err(reason),+ None => Ok(names),+ });+ let user_servers = match checked {Ok(names) => names,- Err(e) => {- tracing::warn!(error = %e, "could not list codex's own MCP servers; not running codex");- let msg = format!(- "⚠️ [{}] kwnt couldn't check which MCP servers your codex config would start ({e}), so it didn't run codex. Check that `codex mcp list` works.",- input.kwant.name- );+ Err(reason) => {+ let msg = format!("⚠️ [{}] {reason}", input.kwant.name);let _ = event_tx.send(RuntimeEvent::TextDelta(msg.clone())).await;let _ = event_tx.send(RuntimeEvent::TurnComplete { tokens: 0, duration_ms: start.elapsed().as_millis() as u64 })diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex e84eeb81..6c60b995 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -332,9 +332,11 @@ async fn claude_cli_gets_mcp_config_without_secrets_in_argv() {assert!(plain.contains("--strict-mcp-config") && !plain.contains("--mcp-config") && !plain.contains("permission-prompt"), "{plain}");}-/// The servers the fake codex reports for `codex mcp list --json`: a quoted name, and one-/// named like kwnt's gateway.-const USER_SERVERS: &str = r#"[{"name":"userdummy","enabled":true},{"name":"user.dot \"q\"","enabled":true},{"name":"kwnt","enabled":true}]"#;+/// The servers the fake codex reports for `codex mcp list --json`, one with a quoted name.+const USER_SERVERS: &str = r#"[{"name":"userdummy","enabled":true},{"name":"user.dot \"q\"","enabled":true}]"#;+/// The same plus a user server named like kwnt's gateway.+const USER_SERVERS_WITH_KWNT: &str =+ r#"[{"name":"userdummy","enabled":true},{"name":"user.dot \"q\"","enabled":true},{"name":"kwnt","enabled":true}]"#;/// Runs a fake codex/grok that logs its argv and whether it got the gateway token env, and/// returns (argv, token env, thinking notes, reply). `mcp_list` is what it prints for@@ -389,7 +391,7 @@ async fn codex_cli_reaches_mcp_only_through_kwnts_gateway() {let tmp = tempdir().unwrap();let (argv, token, notes, _) =fake_agent_run("codex", Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), Some(USER_SERVERS)).await;- // The user's own servers are switched off by (quoted) name; their "kwnt" is overridden, not disabled+ // The user's own servers are switched off by (quoted) nameassert!(argv.contains(r#"-c mcp_servers={kwnt={url="http://127.0.0.1:1/api/mcp/gateway",bearer_token_env_var="KWNT_MCP_GATEWAY_TOKEN",default_tools_approval_mode="approve",startup_timeout_sec=45,tool_timeout_sec=330},"userdummy"={enabled=false},"user.dot \"q\""={enabled=false}} "#),"{argv}"@@ -412,6 +414,27 @@ async fn codex_cli_reaches_mcp_only_through_kwnts_gateway() {assert!(bare.contains("-c mcp_servers={} "), "{bare}");}+/// A user codex server named `kwnt` would merge with the gateway's entry: without a gateway it is+/// switched off like any other, with one the turn is refused rather than run.+#[cfg(target_os = "linux")]+#[tokio::test]+async fn codex_user_server_named_kwnt_is_disabled_or_refused() {+ let (plain, token, _, _) = fake_agent_run("codex", None, Some(USER_SERVERS_WITH_KWNT)).await;+ assert!(+ plain.contains(r#"-c mcp_servers={"userdummy"={enabled=false},"user.dot \"q\""={enabled=false},"kwnt"={enabled=false}} "#),+ "{plain}"+ );+ assert_eq!(token, "unset");++ let tmp = tempdir().unwrap();+ let (argv, token, _, reply) =+ fake_agent_run("codex", Some(ctx(tmp.path(), Arc::new(FixedApprover(true)))), Some(USER_SERVERS_WITH_KWNT)).await;+ assert_eq!(argv, "", "codex exec ran: {argv}");+ assert_eq!(token, "", "codex exec got the env: {token}");+ assert!(reply.contains("MCP server named `kwnt`") && reply.contains("Rename that server"), "{reply}");+ assert!(!reply.contains("gw-secret-token"), "{reply}");+}+#[cfg(target_os = "linux")]#[tokio::test]async fn codex_cli_does_not_run_when_its_servers_cannot_be_listed() {