From 62fd9cc91199989d88f42618dc817b588dd6dbef Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:20:42 +0000 Subject: [PATCH 1/3] crates: run stdio MCP servers in the worker Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Cargo.lock | 1 + crates/factory-runner/Cargo.toml | 1 + crates/factory-runner/src/claude.rs | 61 ++++- crates/factory-runner/src/codex.rs | 81 +++++- crates/factory-runner/src/copilot.rs | 89 +++++- crates/factory-runner/src/lib.rs | 4 +- crates/factory-runner/src/worker.rs | 45 +++- crates/factory-runner/tests/codex.rs | 111 +++++++- crates/factory-runner/tests/copilot.rs | 104 ++++++- crates/factory-runner/tests/runner.rs | 127 ++++++++- crates/factory-server/src/scheduler.rs | 118 ++++++-- crates/factory-server/src/warnings.rs | 8 +- crates/factory-server/tests/scheduler.rs | 330 ++++++++++++++++++++++- docs/design.md | 21 +- 14 files changed, 982 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5b31c390..3c298350 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -574,6 +574,7 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "toml", "tracing", ] diff --git a/crates/factory-runner/Cargo.toml b/crates/factory-runner/Cargo.toml index 3c02d70d..bbc6e0ef 100644 --- a/crates/factory-runner/Cargo.toml +++ b/crates/factory-runner/Cargo.toml @@ -19,3 +19,4 @@ tracing = "0.1.44" [dev-dependencies] tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "net"] } +toml = "1.2.1" diff --git a/crates/factory-runner/src/claude.rs b/crates/factory-runner/src/claude.rs index 41b9f0c2..b602dbcb 100644 --- a/crates/factory-runner/src/claude.rs +++ b/crates/factory-runner/src/claude.rs @@ -16,7 +16,8 @@ use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult}; use crate::outcome::{Expect, event_from_result}; use crate::stream::{StreamItem, parse_line}; use crate::worker::{ - AGENTS_DIR, McpConfig, McpServerEntry, McpUnavailable, SessionRun, WorkerConfig, WorkerRun, + AGENTS_DIR, McpConfig, McpServerEntry, McpUnavailable, STDIO_STARTUP_TIMEOUT_SECS, SessionRun, + WorkerConfig, WorkerRun, }; /// The Claude Code config directory inside the worker, mounted from the job's @@ -92,7 +93,7 @@ impl AgentBackend for ClaudeAgent { "--json-schema".into(), run.expect.schema().to_string(), "--settings".into(), - AGENT_SETTINGS.into(), + settings(run.mcp.as_ref()), session_flag.into(), session_id.clone(), ]; @@ -150,22 +151,56 @@ impl AgentBackend for ClaudeAgent { } } -/// The JSON for `claude --mcp-config`: one `http` entry per active server, each -/// pointing at the proxy and carrying `Authorization: Bearer ` as its -/// only header. No stored credential appears here; the proxy adds it. +/// The JSON for `claude --settings`. A run with a stdio server raises Claude's +/// MCP startup timeout, `MCP_TIMEOUT`, through the settings `env` key, because a +/// first start of a package runner downloads the package and the default is 30 +/// seconds. Settings carry it, so the container gets no `--env` for it. +fn settings(mcp: Option<&McpConfig>) -> String { + let has_stdio = mcp.is_some_and(|mcp| { + mcp.servers + .iter() + .any(|server| matches!(server, McpServerEntry::Stdio { .. })) + }); + if has_stdio { + serde_json::json!({ + "attribution": { "commit": "", "pr": "", "sessionUrl": false }, + "env": { "MCP_TIMEOUT": (STDIO_STARTUP_TIMEOUT_SECS * 1000).to_string() }, + }) + .to_string() + } else { + AGENT_SETTINGS.to_owned() + } +} + +/// The JSON for `claude --mcp-config`: one entry per active server. A remote +/// server is an `http` entry pointing at the proxy and carrying +/// `Authorization: Bearer ` as its only header; no stored credential +/// appears here, the proxy adds it. A stdio server is a `stdio` entry with its +/// command and arguments. fn mcp_config(mcp: &McpConfig) -> String { let servers: serde_json::Map = mcp .servers .iter() - .map(|server| match server { - McpServerEntry::Remote { name } => ( + .filter_map(|server| match server { + McpServerEntry::Remote { name } => { + let proxy = mcp.proxy.as_ref()?; + Some(( + name.clone(), + serde_json::json!({ + "type": "http", + "url": format!("{}/mcp/{name}", proxy.url), + "headers": { "Authorization": format!("Bearer {}", proxy.token) }, + }), + )) + } + McpServerEntry::Stdio { + name, + command, + args, + } => Some(( name.clone(), - serde_json::json!({ - "type": "http", - "url": format!("{}/mcp/{name}", mcp.proxy_url), - "headers": { "Authorization": format!("Bearer {}", mcp.token) }, - }), - ), + serde_json::json!({ "type": "stdio", "command": command, "args": args }), + )), }) .collect(); serde_json::json!({ "mcpServers": servers }).to_string() diff --git a/crates/factory-runner/src/codex.rs b/crates/factory-runner/src/codex.rs index 8a332946..0cccdc7e 100644 --- a/crates/factory-runner/src/codex.rs +++ b/crates/factory-runner/src/codex.rs @@ -16,13 +16,17 @@ use std::ffi::OsString; use std::fs; use std::path::Path; +use std::fmt::Write as _; + use factory_core::Agent; use serde_json::Value; use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, TokenUsage}; use crate::outcome::{Expect, event_from_output, failed_event}; use crate::stream::LogLine; -use crate::worker::{McpServerEntry, SessionRun, WorkerConfig, WorkerRun}; +use crate::worker::{ + McpServerEntry, STDIO_STARTUP_TIMEOUT_SECS, SessionRun, WorkerConfig, WorkerRun, +}; /// The Codex config directory inside the worker, mounted from the job's `codex` /// directory on the host and passed to Codex as `CODEX_HOME`. It keeps the @@ -108,10 +112,16 @@ impl AgentBackend for CodexAgent { } fn secret_env<'a>(&self, run: &'a WorkerRun) -> Vec<(&'static str, &'a str)> { - // The MCP run token, by name only, for a run with at least one active - // server. A run with none passes none, so it gets no token. - match run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) { - Some(mcp) => vec![(MCP_TOKEN_ENV, mcp.token.as_str())], + // The MCP run token, by name only, for a run with at least one remote + // server. A run with none, such as one with only stdio servers, passes + // none, so it gets no token. + match run + .mcp + .as_ref() + .filter(|mcp| !mcp.servers.is_empty()) + .and_then(|mcp| mcp.proxy.as_ref()) + { + Some(proxy) => vec![(MCP_TOKEN_ENV, proxy.token.as_str())], None => Vec::new(), } } @@ -143,24 +153,45 @@ impl AgentBackend for CodexAgent { .as_deref() .unwrap_or_else(|| Agent::Codex.default_effort()) )); - // One remote MCP server per active server, pointed at the proxy. The run - // token is passed by name, not value, so it stays out of the arguments; - // the proxy swaps it for the project's stored headers. A run with no - // active server adds nothing. - if let Some(mcp) = run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) { + // A remote MCP server is pointed at the proxy. The run token is passed + // by name, not value, so it stays out of the arguments; the proxy swaps + // it for the project's stored headers. A stdio server is a command with + // arguments and a startup timeout, since Codex's default is 10 seconds. + // A run with no active server adds nothing. + if let Some(mcp) = run.mcp.as_ref() { for entry in &mcp.servers { match entry { McpServerEntry::Remote { name: server } => { + let Some(proxy) = mcp.proxy.as_ref() else { + continue; + }; codex.push("-c".into()); codex.push(format!( "mcp_servers.{server}.url=\"{}/mcp/{server}\"", - mcp.proxy_url + proxy.url )); codex.push("-c".into()); codex.push(format!( "mcp_servers.{server}.bearer_token_env_var=\"{MCP_TOKEN_ENV}\"" )); } + McpServerEntry::Stdio { + name, + command, + args, + } => { + codex.push("-c".into()); + codex.push(format!( + "mcp_servers.{name}.command={}", + toml_string(command) + )); + codex.push("-c".into()); + codex.push(format!("mcp_servers.{name}.args={}", toml_array(args))); + codex.push("-c".into()); + codex.push(format!( + "mcp_servers.{name}.startup_timeout_sec={STDIO_STARTUP_TIMEOUT_SECS}" + )); + } } } } @@ -173,6 +204,34 @@ impl AgentBackend for CodexAgent { } } +/// `value` as a TOML basic string, which `-c` parses as the override's value. +fn toml_string(value: &str) -> String { + let mut out = String::with_capacity(value.len() + 2); + out.push('"'); + for ch in value.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + ch if ch.is_control() => { + let _ = write!(out, "\\u{:04X}", u32::from(ch)); + } + ch => out.push(ch), + } + } + out.push('"'); + out +} + +fn toml_array(values: &[String]) -> String { + let items: Vec = values.iter().map(|value| toml_string(value)).collect(); + format!("[{}]", items.join(",")) +} + /// Parses one line of `codex exec --json`. A line the factory does not keep, /// such as `turn.started`, `item.started` or `item.updated`, gives nothing. fn parse_codex(expect: Expect, line: &str) -> Vec { diff --git a/crates/factory-runner/src/copilot.rs b/crates/factory-runner/src/copilot.rs index dd73e937..3c6c6332 100644 --- a/crates/factory-runner/src/copilot.rs +++ b/crates/factory-runner/src/copilot.rs @@ -24,7 +24,9 @@ use serde_json::Value; use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult}; use crate::outcome::{Expect, event_from_output, failed_event}; use crate::stream::LogLine; -use crate::worker::{AGENTS_DIR, McpConfig, McpServerEntry, SessionRun, WorkerConfig, WorkerRun}; +use crate::worker::{ + AGENTS_DIR, McpConfig, McpServerEntry, McpUnavailable, SessionRun, WorkerConfig, WorkerRun, +}; /// The Copilot config directory inside the worker, mounted from the job's /// `copilot` directory on the host and passed to Copilot as `COPILOT_HOME`. It @@ -103,8 +105,13 @@ impl AgentBackend for CopilotAgent { } fn secret_env<'a>(&self, run: &'a WorkerRun) -> Vec<(&'static str, &'a str)> { - match run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) { - Some(mcp) => vec![(MCP_TOKEN_ENV, mcp.token.as_str())], + match run + .mcp + .as_ref() + .filter(|mcp| !mcp.servers.is_empty()) + .and_then(|mcp| mcp.proxy.as_ref()) + { + Some(proxy) => vec![(MCP_TOKEN_ENV, proxy.token.as_str())], None => Vec::new(), } } @@ -165,24 +172,42 @@ impl AgentBackend for CopilotAgent { } } -/// The JSON for `copilot --additional-mcp-config`: one `http` entry per active -/// server, each pointing at the proxy with `Authorization: Bearer ${FACTORY_MCP_TOKEN}` -/// and `"tools": ["*"]`. No stored credential appears here; the CLI expands the -/// variable and the proxy swaps the run token for the project's headers. +/// The JSON for `copilot --additional-mcp-config`: one entry per active server, +/// each with `"tools": ["*"]`. A remote server is an `http` entry pointing at the +/// proxy with `Authorization: Bearer ${FACTORY_MCP_TOKEN}`. No stored credential +/// appears here; the CLI expands the variable and the proxy swaps the run token +/// for the project's headers. A stdio server is a `local` entry with its command +/// and arguments. Copilot has no startup timeout setting, so it keeps its own. fn mcp_config(mcp: &McpConfig) -> String { let servers: serde_json::Map = mcp .servers .iter() - .map(|server| match server { - McpServerEntry::Remote { name } => ( + .filter_map(|server| match server { + McpServerEntry::Remote { name } => { + let proxy = mcp.proxy.as_ref()?; + Some(( + name.clone(), + serde_json::json!({ + "type": "http", + "url": format!("{}/mcp/{name}", proxy.url), + "headers": { "Authorization": format!("Bearer ${{{MCP_TOKEN_ENV}}}") }, + "tools": ["*"], + }), + )) + } + McpServerEntry::Stdio { + name, + command, + args, + } => Some(( name.clone(), serde_json::json!({ - "type": "http", - "url": format!("{}/mcp/{name}", mcp.proxy_url), - "headers": { "Authorization": format!("Bearer ${{{MCP_TOKEN_ENV}}}") }, + "type": "local", + "command": command, + "args": args, "tools": ["*"], }), - ), + )), }) .collect(); serde_json::json!({ "mcpServers": servers }).to_string() @@ -199,10 +224,16 @@ fn parse_copilot(expect: Expect, line: &str) -> Vec { let Ok(value) = serde_json::from_str::(line) else { return vec![AgentItem::Log(LogLine::Other(line.to_owned()))]; }; + let data = value.get("data"); + // These two are ephemeral, so they come before the ephemeral check. + match value.get("type").and_then(Value::as_str) { + Some("session.mcp_server_status_changed") => return mcp_status_changed(data), + Some("session.mcp_servers_loaded") => return mcp_servers_loaded(data), + _ => {} + } if value.get("ephemeral").and_then(Value::as_bool) == Some(true) { return Vec::new(); } - let data = value.get("data"); match value.get("type").and_then(Value::as_str) { Some("session.start") => string_at(data, "sessionId") .map(|id| AgentItem::Session(id.to_owned())) @@ -222,6 +253,36 @@ fn parse_copilot(expect: Expect, line: &str) -> Vec { } } +/// A server the agent reports as failed, such as a stdio command that would not +/// start. The reason names the status only, since the CLI's error text can quote +/// the command's output. +fn mcp_unavailable(server: &str, status: &str) -> AgentItem { + AgentItem::Unavailable(McpUnavailable { + server: server.to_owned(), + reason: format!("the agent reported it as {status}"), + }) +} + +fn mcp_status_changed(data: Option<&Value>) -> Vec { + match (string_at(data, "serverName"), string_at(data, "status")) { + (Some(server), Some("failed")) => vec![mcp_unavailable(server, "failed")], + _ => Vec::new(), + } +} + +fn mcp_servers_loaded(data: Option<&Value>) -> Vec { + data.and_then(|data| data.get("servers")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|server| { + let status = server.get("status").and_then(Value::as_str)?; + let name = server.get("name").and_then(Value::as_str)?; + (status == "failed").then(|| mcp_unavailable(name, status)) + }) + .collect() +} + fn parse_message(expect: Expect, data: Option<&Value>) -> Vec { let Some(text) = string_at(data, "content").filter(|text| !text.trim().is_empty()) else { return Vec::new(); diff --git a/crates/factory-runner/src/lib.rs b/crates/factory-runner/src/lib.rs index 814525ae..c29ebb74 100644 --- a/crates/factory-runner/src/lib.rs +++ b/crates/factory-runner/src/lib.rs @@ -44,6 +44,6 @@ pub use outcome::{Expect, event_from_output, event_from_result, failed_event}; pub use prompt::{job_prompt, prompt}; pub use stream::{LogLine, McpServerStatus, ResultMessage, StreamItem, parse_line}; pub use worker::{ - McpConfig, McpServerEntry, McpUnavailable, RunReport, SessionRun, WorkerConfig, WorkerRun, - podman_args, remove_container, run, + McpConfig, McpProxy, McpServerEntry, McpUnavailable, RunReport, STDIO_STARTUP_TIMEOUT_SECS, + SessionRun, WorkerConfig, WorkerRun, podman_args, remove_container, run, }; diff --git a/crates/factory-runner/src/worker.rs b/crates/factory-runner/src/worker.rs index 860a6c14..490d5601 100644 --- a/crates/factory-runner/src/worker.rs +++ b/crates/factory-runner/src/worker.rs @@ -54,23 +54,32 @@ impl Default for WorkerConfig { } } -/// The MCP servers active for one run, and how the worker reaches them. The -/// agent passes each as an `http` entry in its MCP config, pointed at the proxy -/// with the per-run token, so a server credential never enters the worker: the -/// proxy swaps the token for the project's stored headers. The scheduler builds -/// this only when at least one server is active, so a run with none passes no -/// MCP config. +/// The MCP servers active for one run, and how the worker reaches them. A +/// remote server is an `http` entry in the agent's MCP config, pointed at the +/// proxy with the per-run token, so a server credential never enters the worker: +/// the proxy swaps the token for the project's stored headers. A stdio server is +/// a command the agent starts itself inside the worker, so it passes through no +/// proxy and carries no token. The scheduler builds this only when at least one +/// server is active, so a run with none passes no MCP config. #[derive(Debug, Clone, PartialEq, Eq)] pub struct McpConfig { + /// How the worker reaches the proxy. Set only when a remote server is + /// active, so a run with only stdio servers has no token and no URL. + pub proxy: Option, + /// The active servers. Each becomes one entry in the agent's MCP config. + /// Never empty when this is set. + pub servers: Vec, +} + +/// The proxy a run's remote servers go through. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct McpProxy { /// The proxy's base URL the worker reaches, such as `http://factory:8081`. - pub proxy_url: String, + pub url: String, /// The per-run bearer token the proxy checks. It is the entry's only /// header, scoped to this job and these servers, and revoked when the run /// ends. pub token: String, - /// The active servers. Each becomes one entry in the agent's MCP config. - /// Never empty when this is set. - pub servers: Vec, } impl McpConfig { @@ -85,8 +94,16 @@ impl McpConfig { #[derive(Debug, Clone, PartialEq, Eq)] pub enum McpServerEntry { /// A remote server behind the proxy. It becomes one `http` entry keyed by - /// the name, pointing at `/mcp/`. + /// the name, pointing at `/mcp/`. Remote { name: String }, + /// A command the agent starts as a child process in the worker and talks to + /// over stdin and stdout. `args` is the registry's base arguments followed + /// by the project's extra arguments. + Stdio { + name: String, + command: String, + args: Vec, + }, } impl McpServerEntry { @@ -94,11 +111,15 @@ impl McpServerEntry { #[must_use] pub fn name(&self) -> &str { match self { - Self::Remote { name } => name, + Self::Remote { name } | Self::Stdio { name, .. } => name, } } } +/// How long the agent waits for a stdio server to start, in seconds. A first +/// start of a package runner such as `npx` downloads the package. +pub const STDIO_STARTUP_TIMEOUT_SECS: u64 = 120; + /// Whether a run starts the session or continues it. #[derive(Debug, Clone, PartialEq, Eq)] pub enum SessionRun { diff --git a/crates/factory-runner/tests/codex.rs b/crates/factory-runner/tests/codex.rs index 180a74b0..a84db34a 100644 --- a/crates/factory-runner/tests/codex.rs +++ b/crates/factory-runner/tests/codex.rs @@ -10,8 +10,8 @@ use std::path::{Path, PathBuf}; use factory_core::{Agent, AgentResult, Event}; use factory_runner::{ - AgentItem, Expect, LogLine, McpConfig, McpServerEntry, RunResult, SessionRun, TokenUsage, - WorkerConfig, WorkerRun, backend, run, + AgentItem, Expect, LogLine, McpConfig, McpProxy, McpServerEntry, RunResult, SessionRun, + TokenUsage, WorkerConfig, WorkerRun, backend, run, }; use serde_json::Value; @@ -146,8 +146,10 @@ fn the_mcp_token_passes_by_name_only_and_the_login_never_enters_the_arguments() let dir = tempfile::tempdir().unwrap(); let mut run = codex_run(dir.path(), SessionRun::Resume(THREAD.into())); run.mcp = Some(McpConfig { - proxy_url: "http://factory:8081".into(), - token: "d34db33f-run-token".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "d34db33f-run-token".into(), + }), servers: ["context7", "docs"] .map(|name| McpServerEntry::Remote { name: name.into() }) .to_vec(), @@ -188,14 +190,105 @@ fn the_mcp_token_passes_by_name_only_and_the_login_never_enters_the_arguments() ); } +fn stdio_entry() -> McpServerEntry { + McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: ["--no-sandbox", "a \"b\\c\" d"].map(String::from).to_vec(), + } +} + +#[test] +fn a_stdio_server_becomes_toml_overrides_with_a_startup_timeout_and_no_token() { + let dir = tempfile::tempdir().unwrap(); + let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); + let plain = codex_args(&run); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + let args = codex_args(&run); + + let overrides: Vec<&String> = args + .iter() + .filter(|arg| arg.starts_with("mcp_servers.")) + .collect(); + // The quote, backslash and space in the second argument are escaped, so + // TOML reads them back unchanged. + assert_eq!( + overrides, + [ + r#"mcp_servers.pw.command="playwright-mcp""#, + r#"mcp_servers.pw.args=["--no-sandbox","a \"b\\c\" d"]"#, + "mcp_servers.pw.startup_timeout_sec=120", + ] + ); + let value: toml::Value = toml::from_str(&format!( + "args = {}", + overrides[1].strip_prefix("mcp_servers.pw.args=").unwrap() + )) + .unwrap(); + assert_eq!(value["args"][1].as_str(), Some("a \"b\\c\" d")); + + assert!(!env_names(&args).contains(&"FACTORY_MCP_TOKEN"), "{args:?}"); + assert!(!args.iter().any(|arg| arg.contains("factory:8081"))); + // No container flag is added: only the config overrides differ. + let flags = |args: &[String]| args.iter().filter(|a| a.starts_with("--")).count(); + assert_eq!(flags(&args), flags(&plain)); + assert_eq!(env_names(&args), env_names(&plain)); +} + +#[test] +fn a_remote_and_a_stdio_server_share_a_codex_run() { + let dir = tempfile::tempdir().unwrap(); + let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); + run.mcp = Some(McpConfig { + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "tok".into(), + }), + servers: vec![ + McpServerEntry::Remote { + name: "context7".into(), + }, + stdio_entry(), + ], + }); + let args = codex_args(&run); + assert!( + args.iter() + .any(|arg| { arg == "mcp_servers.context7.url=\"http://factory:8081/mcp/context7\"" }) + ); + assert!( + args.iter() + .any(|arg| arg.starts_with("mcp_servers.pw.command=")) + ); + assert!(env_names(&args).contains(&"FACTORY_MCP_TOKEN")); +} + +#[test] +fn a_stdio_tool_call_logs_the_namespaced_tool_name() { + let line = r#"{"type":"item.completed","item":{"id":"item_1","type":"mcp_tool_call","server":"pw","tool":"browser_navigate","status":"completed"}}"#; + let items = backend(Agent::Codex).unwrap().parse(Expect::Spec, line); + assert!( + items.iter().any(|item| matches!( + item, + AgentItem::Log(LogLine::Tool { name, .. }) if name == "mcp__pw__browser_navigate" + )), + "{items:?}" + ); +} + #[test] fn a_run_with_no_active_server_passes_no_mcp_flags_or_token() { let dir = tempfile::tempdir().unwrap(); for mcp in [None, Some(Vec::new())] { let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); run.mcp = mcp.map(|servers| McpConfig { - proxy_url: "http://factory:8081".into(), - token: "unused".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "unused".into(), + }), servers, }); let args = codex_args(&run); @@ -224,8 +317,10 @@ fn a_claude_run_is_unchanged_by_the_codex_backend() { model: None, effort: None, mcp: Some(McpConfig { - proxy_url: "http://factory:8081".into(), - token: "run-token".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "run-token".into(), + }), servers: vec![McpServerEntry::Remote { name: "context7".into(), }], diff --git a/crates/factory-runner/tests/copilot.rs b/crates/factory-runner/tests/copilot.rs index 8a6314a1..97b0250c 100644 --- a/crates/factory-runner/tests/copilot.rs +++ b/crates/factory-runner/tests/copilot.rs @@ -12,8 +12,8 @@ use std::path::{Path, PathBuf}; use factory_core::{Agent, AgentResult, Event, PrDescription}; use factory_runner::{ - AgentItem, Expect, LogLine, McpConfig, McpServerEntry, RunResult, SessionRun, WorkerConfig, - WorkerRun, backend, run, + AgentItem, Expect, LogLine, McpConfig, McpProxy, McpServerEntry, McpUnavailable, RunResult, + SessionRun, WorkerConfig, WorkerRun, backend, run, }; const SESSION: &str = "d3c2f38c-6c9e-4528-9666-a9c3d7aff405"; @@ -156,8 +156,10 @@ fn the_mcp_token_passes_by_name_only_and_the_login_never_enters_the_arguments() let dir = tempfile::tempdir().unwrap(); let mut run = copilot_run(dir.path(), SessionRun::Resume(SESSION.into())); run.mcp = Some(McpConfig { - proxy_url: "http://factory:8081".into(), - token: "d34db33f-run-token".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "d34db33f-run-token".into(), + }), servers: ["context7", "docs"] .map(|name| McpServerEntry::Remote { name: name.into() }) .to_vec(), @@ -193,14 +195,104 @@ fn the_mcp_token_passes_by_name_only_and_the_login_never_enters_the_arguments() ); } +fn stdio_entry() -> McpServerEntry { + McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: ["--no-sandbox", "a $b"].map(String::from).to_vec(), + } +} + +#[test] +fn a_stdio_server_becomes_a_local_entry_with_no_token() { + let dir = tempfile::tempdir().unwrap(); + let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); + let plain = copilot_args(&run); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + let args = copilot_args(&run); + + let config: serde_json::Value = + serde_json::from_str(value_after(&args, "--additional-mcp-config")).unwrap(); + assert_eq!( + config["mcpServers"], + serde_json::json!({ "pw": { + "type": "local", + "command": "playwright-mcp", + "args": ["--no-sandbox", "a $b"], + "tools": ["*"], + } }) + ); + assert!(!env_names(&args).contains(&"FACTORY_MCP_TOKEN"), "{args:?}"); + assert!(!args.iter().any(|arg| arg.contains("factory:8081"))); + assert_eq!(env_names(&args), env_names(&plain)); +} + +#[test] +fn a_remote_and_a_stdio_server_share_a_copilot_run() { + let dir = tempfile::tempdir().unwrap(); + let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); + run.mcp = Some(McpConfig { + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "tok".into(), + }), + servers: vec![ + McpServerEntry::Remote { + name: "context7".into(), + }, + stdio_entry(), + ], + }); + let args = copilot_args(&run); + let config: serde_json::Value = + serde_json::from_str(value_after(&args, "--additional-mcp-config")).unwrap(); + assert_eq!(config["mcpServers"]["context7"]["type"], "http"); + assert_eq!(config["mcpServers"]["pw"]["type"], "local"); + assert!(env_names(&args).contains(&"FACTORY_MCP_TOKEN")); +} + +#[test] +fn a_stdio_tool_start_logs_the_namespaced_tool_name() { + let line = r#"{"type":"tool.execution_start","data":{"toolName":"pw-browser_navigate","mcpServerName":"pw","mcpToolName":"browser_navigate","arguments":{},"toolCallId":"t1"}}"#; + assert_eq!( + parse(Expect::Spec, line), + [AgentItem::Log(LogLine::Tool { + name: "mcp__pw__browser_navigate".into(), + summary: String::new() + })] + ); +} + +#[test] +fn a_failed_server_status_is_reported_unavailable_even_though_it_is_ephemeral() { + let changed = r#"{"type":"session.mcp_server_status_changed","ephemeral":true,"data":{"serverName":"pw","status":"failed","error":"spawn ENOENT"}}"#; + let connected = r#"{"type":"session.mcp_server_status_changed","ephemeral":true,"data":{"serverName":"ok","status":"connected"}}"#; + let loaded = r#"{"type":"session.mcp_servers_loaded","ephemeral":true,"data":{"servers":[{"name":"ok","status":"connected"},{"name":"pw","status":"failed","error":"spawn ENOENT"}]}}"#; + let expected = AgentItem::Unavailable(McpUnavailable { + server: "pw".into(), + reason: "the agent reported it as failed".into(), + }); + assert_eq!( + parse(Expect::Spec, changed), + std::slice::from_ref(&expected) + ); + assert_eq!(parse(Expect::Spec, connected), []); + assert_eq!(parse(Expect::Spec, loaded), [expected]); +} + #[test] fn a_run_with_no_active_server_passes_no_mcp_config_or_token() { let dir = tempfile::tempdir().unwrap(); for mcp in [None, Some(Vec::new())] { let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); run.mcp = mcp.map(|servers| McpConfig { - proxy_url: "http://factory:8081".into(), - token: "unused".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "unused".into(), + }), servers, }); let args = copilot_args(&run); diff --git a/crates/factory-runner/tests/runner.rs b/crates/factory-runner/tests/runner.rs index 9675278a..6557d331 100644 --- a/crates/factory-runner/tests/runner.rs +++ b/crates/factory-runner/tests/runner.rs @@ -8,10 +8,10 @@ use factory_core::{ PrDescription, Question, Stage, Task, UsageWindow, }; use factory_runner::{ - Expect, LogLine, McpConfig, McpServerEntry, McpServerStatus, PlacedFile, ResultMessage, - SessionRun, StreamItem, WorkerConfig, WorkerRun, backend, event_from_result, job_prompt, - parse_line, place_files, place_images, podman_args, prompt, remove_container, run, show_files, - show_images, + AgentItem, Expect, LogLine, McpConfig, McpProxy, McpServerEntry, McpServerStatus, + McpUnavailable, PlacedFile, ResultMessage, SessionRun, StreamItem, WorkerConfig, WorkerRun, + backend, event_from_result, job_prompt, parse_line, place_files, place_images, podman_args, + prompt, remove_container, run, show_files, show_images, }; use serde_json::{Value, json}; @@ -951,8 +951,10 @@ fn podman_args_pass_no_mcp_config_without_an_active_server() { for mcp in [None, Some(Vec::new())] { let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); run.mcp = mcp.map(|servers| McpConfig { - proxy_url: "http://factory:8081".into(), - token: "unused".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "unused".into(), + }), servers, }); let args = strings(&podman_args(&WorkerConfig::default(), &run)); @@ -964,8 +966,10 @@ fn podman_args_pass_no_mcp_config_without_an_active_server() { fn podman_args_give_each_active_server_a_proxy_entry_with_the_run_token() { let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Resume(SESSION.into())); run.mcp = Some(McpConfig { - proxy_url: "http://factory:8081".into(), - token: "d34db33f".into(), + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "d34db33f".into(), + }), servers: ["context7", "docs"] .map(|name| McpServerEntry::Remote { name: name.into() }) .to_vec(), @@ -991,6 +995,113 @@ fn podman_args_give_each_active_server_a_proxy_entry_with_the_run_token() { } } +fn stdio_entry() -> McpServerEntry { + McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: ["--no-sandbox", "--headless", "a b\"c$"] + .map(String::from) + .to_vec(), + } +} + +#[test] +fn podman_args_give_a_stdio_server_a_command_entry_and_no_token_or_proxy() { + let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Resume(SESSION.into())); + let plain = strings(&podman_args(&WorkerConfig::default(), &run)); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + let args = strings(&podman_args(&WorkerConfig::default(), &run)); + + let config: Value = serde_json::from_str(value_after(&args, "--mcp-config")).unwrap(); + assert_eq!( + config["mcpServers"], + json!({ "pw": { + "type": "stdio", + "command": "playwright-mcp", + "args": ["--no-sandbox", "--headless", "a b\"c$"], + } }) + ); + assert!(!args.iter().any(|arg| arg.contains("FACTORY_MCP_TOKEN"))); + assert!(!args.iter().any(|arg| arg.contains("factory:8081"))); + + // The startup timeout rides in the settings, not a container flag. + let settings: Value = serde_json::from_str(value_after(&args, "--settings")).unwrap(); + assert_eq!(settings["env"]["MCP_TIMEOUT"], "120000"); + assert_eq!(settings["attribution"]["sessionUrl"], false); + + // The stdio server adds no container flag: every podman flag before the + // image is the same as without it. + let image = |args: &[String]| args.iter().position(|arg| arg == "claude").unwrap(); + assert_eq!(args[..image(&args)], plain[..image(&plain)]); +} + +#[test] +fn podman_args_carry_a_remote_and_a_stdio_server_together() { + let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); + run.mcp = Some(McpConfig { + proxy: Some(McpProxy { + url: "http://factory:8081".into(), + token: "d34db33f".into(), + }), + servers: vec![ + McpServerEntry::Remote { + name: "context7".into(), + }, + stdio_entry(), + ], + }); + let args = strings(&podman_args(&WorkerConfig::default(), &run)); + let config: Value = serde_json::from_str(value_after(&args, "--mcp-config")).unwrap(); + assert_eq!( + config["mcpServers"]["context7"], + json!({ + "type": "http", + "url": "http://factory:8081/mcp/context7", + "headers": { "Authorization": "Bearer d34db33f" }, + }) + ); + assert_eq!(config["mcpServers"]["pw"]["type"], "stdio"); +} + +#[test] +fn a_run_without_a_stdio_server_keeps_the_settings_it_had() { + let run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); + let args = strings(&podman_args(&WorkerConfig::default(), &run)); + assert_eq!( + value_after(&args, "--settings"), + r#"{"attribution":{"commit":"","pr":"","sessionUrl":false}}"# + ); +} + +#[test] +fn a_failed_stdio_server_in_the_init_line_is_reported_unavailable() { + let line = r#"{"type":"system","subtype":"init","session_id":"s","mcp_servers":[{"name":"pw","status":"failed","source":"dynamic"}]}"#; + let items = backend(Agent::Claude).unwrap().parse(Expect::Spec, line); + assert_eq!( + items, + vec![AgentItem::Unavailable(McpUnavailable { + server: "pw".into(), + reason: "the agent reported it as failed".into(), + })] + ); +} + +#[test] +fn a_stdio_tool_use_logs_the_namespaced_tool_name() { + let line = r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"mcp__pw__browser_navigate","input":{"url":"http://localhost:3000"}}]}}"#; + let items = backend(Agent::Claude).unwrap().parse(Expect::Spec, line); + assert!( + items.iter().any(|item| matches!( + item, + AgentItem::Log(LogLine::Tool { name, .. }) if name == "mcp__pw__browser_navigate" + )), + "{items:?}" + ); +} + #[test] fn podman_args_attach_the_worker_to_the_configured_network() { let config = WorkerConfig { diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 85a80287..7e316eed 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -12,8 +12,8 @@ use factory_core::{ ReviewState, Session, Stage, }; use factory_runner::{ - Expect, ForgeKind, HeadCommit, LogLine, McpConfig, McpServerEntry, NOT_PERMITTED, Observation, - RenovatePr, Rerun, RunReport, job_prompt, + Expect, ForgeKind, HeadCommit, LogLine, McpConfig, McpProxy, McpServerEntry, NOT_PERMITTED, + Observation, RenovatePr, Rerun, RunReport, job_prompt, }; use tokio::sync::Notify; use tokio::time::Instant; @@ -585,10 +585,29 @@ struct McpSelection { skipped: Vec, } +/// One server active for a run, with what the run's config needs from the +/// registry and the project. +enum ActiveServer { + Remote(String), + Stdio { + name: String, + command: String, + args: Vec, + }, +} + +impl ActiveServer { + fn name(&self) -> &str { + match self { + Self::Remote(name) | Self::Stdio { name, .. } => name, + } + } +} + /// The servers active for a run and the servers skipped for an undecryptable /// secret, as [`Scheduler::active_mcp_servers`] sorts them. struct ActiveServers { - active: Vec, + active: Vec, skipped: Vec, } @@ -607,6 +626,14 @@ impl Drop for TokenGuard { } } +/// The server and tool of an agent's `mcp____` tool name when the +/// server is one of the run's stdio servers. Server names hold no underscore, so +/// the first `__` after the prefix ends the server. +fn stdio_tool_call<'a>(name: &'a str, stdio: &[String]) -> Option<(&'a str, &'a str)> { + let (server, tool) = name.strip_prefix("mcp__")?.split_once("__")?; + stdio.iter().any(|s| s == server).then_some((server, tool)) +} + /// Clears a run's MCP warning dedup state when the run ends, by success, /// failure or cancel. A cancel aborts the run's task and drops its future, so /// `Drop` is the only point that fires in every case, like [`TokenGuard`]. @@ -1350,16 +1377,34 @@ impl Scheduler { expect: Expect, ) -> Result { let ActiveServers { active, skipped } = self.active_mcp_servers(project, expect)?; - let config = (!active.is_empty()).then(|| { - let token = self.mcp.tokens.issue(job_id, project, &active); - McpConfig { - proxy_url: self.mcp.proxy_url.clone(), - token, - servers: active - .into_iter() - .map(|name| McpServerEntry::Remote { name }) - .collect(), - } + let remote: Vec = active + .iter() + .filter(|server| matches!(server, ActiveServer::Remote(_))) + .map(|server| server.name().to_owned()) + .collect(); + // Only a remote server goes through the proxy, so a run with stdio + // servers alone gets no token. + let proxy = (!remote.is_empty()).then(|| McpProxy { + url: self.mcp.proxy_url.clone(), + token: self.mcp.tokens.issue(job_id, project, &remote), + }); + let config = (!active.is_empty()).then(|| McpConfig { + proxy, + servers: active + .into_iter() + .map(|server| match server { + ActiveServer::Remote(name) => McpServerEntry::Remote { name }, + ActiveServer::Stdio { + name, + command, + args, + } => McpServerEntry::Stdio { + name, + command, + args, + }, + }) + .collect(), }); Ok(McpSelection { config, skipped }) } @@ -1391,12 +1436,18 @@ impl Scheduler { if !(settings.enabled && in_stage) { continue; } - // Runs do not carry stdio servers yet. - if server.as_stdio().is_some() { - continue; - } - if self.mcp_secrets_usable(project, &server)? { - active.push(server.name); + if let Some((command, base)) = server.as_stdio() { + // The project's extra arguments follow the base arguments, read + // on every run so a change reaches the job's next run. + let mut args = base.to_vec(); + args.extend(self.store.project_mcp_args(project, &server.name)?); + active.push(ActiveServer::Stdio { + command: command.to_owned(), + args, + name: server.name, + }); + } else if self.mcp_secrets_usable(project, &server)? { + active.push(ActiveServer::Remote(server.name)); } else { skipped.push(( server.name, @@ -1651,10 +1702,14 @@ impl Scheduler { let job_id = request.job_id; // The run's proxy token is revoked when this guard drops: at the end of // the run, or when a cancel aborts and drops this future. - let _token = request.mcp.as_ref().map(|mcp| TokenGuard { - tokens: Arc::clone(&self.mcp.tokens), - token: mcp.token.clone(), - }); + let _token = request + .mcp + .as_ref() + .and_then(|mcp| mcp.proxy.as_ref()) + .map(|proxy| TokenGuard { + tokens: Arc::clone(&self.mcp.tokens), + token: proxy.token.clone(), + }); // Forget the servers warned about in this job's previous run before this // one reports any, and clear this run's set when the guard drops, so a // server is warned about at most once per run. Begun before the worker @@ -1681,7 +1736,24 @@ impl Scheduler { &format!("Agent run started in session {session_label}."), ); let sink_store = Arc::clone(&self.store); + // The proxy records a call to a remote server. A call to a stdio server + // never reaches it, so the run's own output is the record. + let stdio_servers: Vec = request + .mcp + .iter() + .flat_map(|mcp| &mcp.servers) + .filter_map(|entry| match entry { + McpServerEntry::Stdio { name, .. } => Some(name.clone()), + McpServerEntry::Remote { .. } => None, + }) + .collect(); + let call_warnings = Arc::clone(&self.mcp.warnings); let sink: LogSink = Box::new(move |line| { + if let LogLine::Tool { name, .. } = &line + && let Some((server, tool)) = stdio_tool_call(name, &stdio_servers) + { + call_warnings.record_tool_called(job_id, server, tool); + } if let Err(err) = sink_store.append_log(job_id, &line) { tracing::error!("job {job_id}: {err}"); } diff --git a/crates/factory-server/src/warnings.rs b/crates/factory-server/src/warnings.rs index 8692425b..8075825d 100644 --- a/crates/factory-server/src/warnings.rs +++ b/crates/factory-server/src/warnings.rs @@ -13,9 +13,11 @@ //! `job_events`, neither of which changes the job's stage or turn. //! //! A refused tool call comes only from the proxy. It writes a factory line to -//! the job log and an `mcp-tool-blocked` row to `job_events`. A forwarded call -//! comes only from the proxy too and writes an `mcp-tool-call` row, with no log -//! line and no dedup, so every call the agent makes is one row. +//! the job log and an `mcp-tool-blocked` row to `job_events`. A call to a remote +//! server comes from the proxy and writes an `mcp-tool-call` row, with no log +//! line and no dedup. A call to a stdio server never reaches the proxy, so the +//! scheduler writes the same row from the agent's output. Every call the agent +//! makes is one row. //! //! The dedup is keyed by job. A job runs one agent run at a time, so //! [`McpWarnings::begin`] clears the servers warned in the job's previous run diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index 753f0e2a..737cf78e 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -9,17 +9,17 @@ use factory_core::{ ReviewState, Stage, Turn, Wait, }; use factory_runner::{ - Account, Expect, ForgeAccount, ForgeKind, Git, GitHub, HeadCommit, LogLine, McpUnavailable, - NOT_PERMITTED, Observation, RenovatePr, Rerun, RunReport, TokenUsage, WorkerConfig, - is_renovate_login, + Account, Expect, ForgeAccount, ForgeKind, Git, GitHub, HeadCommit, LogLine, McpServerEntry, + McpUnavailable, NOT_PERMITTED, Observation, RenovatePr, Rerun, RunReport, TokenUsage, + WorkerConfig, is_renovate_login, }; use factory_server::{ AccountSource, Accounts, AgentRegistry, AgentRequest, ChecksRequest, ClaudeToken, CodexLogin, CodexPrice, Executor, FACTORY_REQUESTER, ForgeTokenOwner, Forges, GhRepos, JobFile, - LocalSecrets, LogSink, MASTER_KEY_LEN, McpProjectSettings, McpRuntime, McpStages, McpWarnings, - Owner, PlanUsageCache, PodmanExecutor, PrerequisiteEdit, Project, ProjectForge, Projects, - PublishRequest, Published, ReadyAction, Rebase, RenovateWatchRequest, RerunRequest, RunTokens, - Scheduler, SecretRef, SecretStore, SessionSink, Settings, StageAgents, StageEfforts, + LocalSecrets, LogSink, MASTER_KEY_LEN, McpProjectSettings, McpRuntime, McpStages, McpTransport, + McpWarnings, Owner, PlanUsageCache, PodmanExecutor, PrerequisiteEdit, Project, ProjectForge, + Projects, PublishRequest, Published, ReadyAction, Rebase, RenovateWatchRequest, RerunRequest, + RunTokens, Scheduler, SecretRef, SecretStore, SessionSink, Settings, StageAgents, StageEfforts, StageModels, Store, SummaryRequest, UnavailableSecrets, UpstreamCredential, WatchReport, WatchRequest, WorkerSlots, credential_failure, format_cost, ready_action, watch_only_event, }; @@ -46,6 +46,7 @@ struct FakeExecutor { token_usages: Mutex>, /// The MCP servers each run reports as not connected in its init line. unavailable: Mutex>>, + tool_calls: Mutex>>, /// The agent-reported session ids each run streams back, such as Codex's /// thread id, in run order. A run with none reports no id, as Claude does. sessions: Mutex>, @@ -116,6 +117,7 @@ impl FakeExecutor { costs: Mutex::new(VecDeque::new()), token_usages: Mutex::new(VecDeque::new()), unavailable: Mutex::new(VecDeque::new()), + tool_calls: Mutex::new(VecDeque::new()), sessions: Mutex::new(VecDeque::new()), stopped: Mutex::new(Vec::new()), stop_gate: Semaphore::new(Semaphore::MAX_PERMITS), @@ -171,6 +173,15 @@ impl FakeExecutor { self.unavailable.lock().unwrap().push_back(servers); } + /// Makes the next run log a tool call for each of `names`, the way the + /// agent's output does. + fn report_tool_calls(&self, names: &[&str]) { + self.tool_calls + .lock() + .unwrap() + .push_back(names.iter().map(|name| (*name).to_owned()).collect()); + } + /// Makes the next run stream back `id` as the agent's own session id, the /// way a Codex run reports its thread id on `thread.started`. fn report_session(&self, id: &str) { @@ -198,6 +209,14 @@ impl Executor for FakeExecutor { session(id); } log(LogLine::Text("Reading the repository.".into())); + // The tool names the test queued, logged the way the agent's output is. + let tools = self.tool_calls.lock().unwrap().pop_front(); + for name in tools.into_iter().flatten() { + log(LogLine::Tool { + name, + summary: String::new(), + }); + } // A run with queued token usage reports it and no dollar cost, the way a // Codex run does; otherwise it reports a dollar cost like Claude. let token_usage = self.token_usages.lock().unwrap().pop_front(); @@ -4529,6 +4548,294 @@ async fn a_server_whose_secret_cannot_be_decrypted_is_skipped_with_a_warning() { ); } +/// Like [`setup_mcp`] with a second project, `factory`. +fn setup_two_projects( + respond: impl Fn(&AgentRequest) -> Event + Send + Sync + 'static, +) -> (Arc, Arc, Arc>) { + let store = Arc::new(Store::open_in_memory().unwrap()); + let executor = FakeExecutor::new(respond); + let project = |repo: &str| Project { + forge: ProjectForge::Known(ForgeKind::GitHub), + repo: repo.into(), + base: "main".into(), + checks: Some("just lint".into()), + models: factory_server::StageModels::default(), + auto_merge: false, + llm_review: false, + }; + let projects: Projects = [ + ("maestro".to_owned(), project("Badger-Embedded/maestro")), + ("factory".to_owned(), project("Badger-Embedded/factory")), + ] + .into_iter() + .collect(); + let scheduler = Scheduler::new( + Arc::clone(&store), + Arc::new(projects), + Arc::clone(&executor), + Arc::new(Notify::new()), + PathBuf::new(), + mcp_runtime(&store).0, + accounts(&store), + ); + (store, executor, scheduler) +} + +fn clarify_only() -> McpStages { + McpStages { + clarify: true, + ..Default::default() + } +} + +fn stdio_entry(request: &AgentRequest, name: &str) -> Option<(String, Vec)> { + request + .mcp + .iter() + .flat_map(|mcp| &mcp.servers) + .find_map(|entry| match entry { + McpServerEntry::Stdio { + name: n, + command, + args, + } if n == name => Some((command.clone(), args.clone())), + _ => None, + }) +} + +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +fn register_stdio(store: &Store, name: &str, command: &str, args: &[&str]) { + store + .create_mcp_server_with( + name, + &McpTransport::Stdio { + command: command.into(), + args: strings(args), + }, + ) + .unwrap(); +} + +#[tokio::test] +async fn a_stdio_run_carries_the_base_arguments_then_the_projects_and_no_token() { + let (store, executor, scheduler, _tokens) = setup_mcp(|_| questions()); + register_stdio(&store, "pw", "playwright-mcp", &["-y", "pkg"]); + store + .save_project_mcp("maestro", "pw", &enabled(clarify_only())) + .unwrap(); + let id = store + .create("maestro", "alice", "Add a reboot button") + .unwrap(); + + // A project with no extra arguments gets the base arguments alone. + scheduler.tick().await.unwrap(); + executor.release(1); + wait_idle(&scheduler).await; + let first = executor.requests()[0].clone(); + assert_eq!( + stdio_entry(&first, "pw"), + Some(("playwright-mcp".into(), strings(&["-y", "pkg"]))) + ); + assert!( + first.mcp.as_ref().unwrap().proxy.is_none(), + "stdio servers alone issue no run token" + ); + assert!( + first + .prompt + .contains("This run has these MCP servers: `pw`.") + ); + + // The job's next run reads the changed list. + store + .save_project_mcp_args("maestro", "pw", &strings(&["--headless", "--x=1"])) + .unwrap(); + store.apply(id, Event::Answer(vec!["rpi5".into()])).unwrap(); + scheduler.tick().await.unwrap(); + executor.release(1); + wait_idle(&scheduler).await; + let second = executor.requests()[1].clone(); + assert_eq!( + stdio_entry(&second, "pw").unwrap().1, + strings(&["-y", "pkg", "--headless", "--x=1"]) + ); +} + +#[tokio::test] +async fn a_stdio_server_enabled_for_implement_alone_reaches_only_the_implement_run() { + let (store, executor, scheduler) = setup(|request| match request.expect { + Expect::Review => Event::ReviewApproved, + _ => Event::Agent(AgentResult::CommitsReady(ready())), + }); + quick_polls(&store); + register_stdio(&store, "pw", "playwright-mcp", &["--no-sandbox"]); + store + .save_project_mcp( + "maestro", + "pw", + &enabled(McpStages { + implement: true, + ..Default::default() + }), + ) + .unwrap(); + + to_watching(&store, &executor, &scheduler).await; + let requests = executor.requests(); + let implement = requests + .iter() + .find(|r| r.expect == Expect::Commits) + .expect("an implement run"); + let entry = stdio_entry(implement, "pw").expect("the implement run carries it"); + assert_eq!(entry.1, strings(&["--no-sandbox"])); + assert!(implement.mcp.as_ref().unwrap().proxy.is_none()); + for request in requests.iter().filter(|r| r.expect != Expect::Commits) { + assert!(request.mcp.is_none(), "{:?}", request.expect); + } +} + +#[tokio::test] +async fn two_projects_get_their_own_extra_arguments_for_the_same_stdio_server() { + let (store, executor, scheduler) = setup_two_projects(|_| questions()); + register_stdio(&store, "pw", "playwright-mcp", &["--no-sandbox"]); + for (project, arg) in [("maestro", "--headless"), ("factory", "--caps=vision")] { + store + .save_project_mcp(project, "pw", &enabled(clarify_only())) + .unwrap(); + store + .save_project_mcp_args(project, "pw", &strings(&[arg])) + .unwrap(); + } + store.create("maestro", "alice", "one").unwrap(); + store.create("factory", "alice", "two").unwrap(); + + scheduler.tick().await.unwrap(); + executor.release(2); + wait_idle(&scheduler).await; + let requests = executor.requests(); + let args_of = |repo: &str| { + let request = requests.iter().find(|r| r.repo.ends_with(repo)).unwrap(); + stdio_entry(request, "pw").unwrap().1 + }; + assert_eq!(args_of("maestro"), strings(&["--no-sandbox", "--headless"])); + assert_eq!( + args_of("factory"), + strings(&["--no-sandbox", "--caps=vision"]) + ); + + // Saving one project's list leaves the other's alone. + store + .save_project_mcp_args("maestro", "pw", &strings(&["--changed"])) + .unwrap(); + assert_eq!( + store.project_mcp_args("factory", "pw").unwrap(), + strings(&["--caps=vision"]) + ); +} + +#[tokio::test] +async fn a_project_that_leaves_a_stdio_server_off_gets_no_mcp_config() { + let (store, executor, scheduler) = setup_two_projects(|_| questions()); + register_stdio(&store, "pw", "playwright-mcp", &[]); + store + .save_project_mcp("maestro", "pw", &enabled(clarify_only())) + .unwrap(); + store.create("maestro", "alice", "one").unwrap(); + store.create("factory", "alice", "two").unwrap(); + + scheduler.tick().await.unwrap(); + executor.release(2); + wait_idle(&scheduler).await; + let requests = executor.requests(); + let mcp_of = |repo: &str| { + requests + .iter() + .find(|r| r.repo.ends_with(repo)) + .unwrap() + .mcp + .clone() + }; + assert!(mcp_of("maestro").is_some()); + assert!(mcp_of("factory").is_none()); +} + +#[tokio::test] +async fn a_run_with_a_remote_and_a_stdio_server_carries_both_and_the_token() { + let (store, executor, scheduler, tokens) = setup_mcp(|_| questions()); + store + .create_mcp_server("context7", "https://mcp.context7.com/mcp", &[]) + .unwrap(); + register_stdio(&store, "pw", "playwright-mcp", &["--no-sandbox"]); + for name in ["context7", "pw"] { + store + .save_project_mcp("maestro", name, &enabled(clarify_only())) + .unwrap(); + } + store.create("maestro", "alice", "one").unwrap(); + + scheduler.tick().await.unwrap(); + wait_for_requests(&executor, 1).await; + let mcp = executor.requests()[0].mcp.clone().unwrap(); + assert_eq!( + mcp.servers, + vec![ + McpServerEntry::Remote { + name: "context7".into() + }, + McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: strings(&["--no-sandbox"]), + }, + ] + ); + let proxy = mcp.proxy.expect("the remote server needs the proxy"); + assert!(tokens.is_active(&proxy.token)); + executor.release(1); + wait_idle(&scheduler).await; +} + +#[tokio::test] +async fn a_stdio_tool_call_in_the_agents_output_is_recorded_under_its_job() { + let (store, executor, scheduler) = setup_two_projects(|_| questions()); + store + .create_mcp_server("context7", "https://mcp.context7.com/mcp", &[]) + .unwrap(); + register_stdio(&store, "pw", "playwright-mcp", &[]); + for name in ["context7", "pw"] { + store + .save_project_mcp("maestro", name, &enabled(clarify_only())) + .unwrap(); + } + let id = store.create("maestro", "alice", "one").unwrap(); + let other = store.create("factory", "alice", "two").unwrap(); + executor.report_tool_calls(&[ + "mcp__pw__browser_navigate", + "mcp__context7__query-docs", + "Bash", + ]); + + scheduler.tick().await.unwrap(); + executor.release(2); + wait_idle(&scheduler).await; + + let calls = |job| -> Vec { + store + .events(job) + .unwrap() + .into_iter() + .filter(|event| event.event == "mcp-tool-call") + .filter_map(|event| event.detail) + .collect() + }; + // A remote call is the proxy's to record, so only the stdio call is a row. + assert_eq!(calls(id), ["pw: browser_navigate"]); + assert_eq!(calls(other), Vec::::new()); +} + #[tokio::test] async fn a_run_token_is_live_during_the_run_and_revoked_after() { let (store, executor, scheduler, tokens) = setup_mcp(|_| questions()); @@ -4556,15 +4863,16 @@ async fn a_run_token_is_live_during_the_run_and_revoked_after() { .clone() .expect("context7 is active for the clarify run"); assert_eq!(mcp.names(), ["context7"]); - assert_eq!(mcp.proxy_url, "http://factory:8081"); - assert!(mcp.token.len() >= 64, "a 256-bit token as hex"); + let proxy = mcp.proxy.expect("a remote server comes with the proxy"); + assert_eq!(proxy.url, "http://factory:8081"); + assert!(proxy.token.len() >= 64, "a 256-bit token as hex"); // The worker is still running, so the proxy honours its token. - assert!(tokens.is_active(&mcp.token)); + assert!(tokens.is_active(&proxy.token)); executor.release(1); wait_idle(&scheduler).await; // The worker exited, so the factory revoked the token. - assert!(!tokens.is_active(&mcp.token)); + assert!(!tokens.is_active(&proxy.token)); } #[tokio::test] diff --git a/docs/design.md b/docs/design.md index f7558301..a2a4a83b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -25,7 +25,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | Factory stack | axum, SQLite, server-rendered pages with htmx, and server-sent events for live logs. No frontend build step. | | Dashboard access | The factory listens on localhost. `tailscale serve` publishes it over HTTPS on the tailnet and passes the Tailscale login in request headers. No separate login. A login sees and acts on a project, and every job in it, only when it is one of the project's collaborators, see Project collaborators. `web.rs` reads this through two helpers: `visible_project` returns the named project when the login collaborates on it, and `visible_job` returns a job when the login collaborates on the job's project. A project the login may not see returns the same 404 as one that was never onboarded, and a job it may not see returns the same 404 as an unknown job, so neither leaks its existence through a different status or page. The board, the project picker, `/fragments/board`, `/fragments/stats`, `/fragments/workers`, `POST /jobs`, every `/jobs/{id}` route, and `/settings/projects/{project}`, its `/checks` and `/name` save routes, and its MCP pages and check all go through these helpers. The board's default project is the one in the `factory_project` cookie when the login collaborates on it, otherwise the first project the login collaborates on. A stale, foreign or malformed cookie falls back silently with no 404, see Remembered project. A login that collaborates on none sees "You are not a collaborator on any project." with a link to onboarding, and the worker and plan-usage tiles, which carry factory-wide data, render only once the login has a project. The board loads the login's projects with one `Store::projects_for` call, also when it checks the project cookie, and filters the already-loaded list in memory, so the checks add no query per job. The worker slots are account-wide, so a tile may hold a job in a project the viewer may not see; such a tile shows only that the slot is busy and for how long, not the job's id, project, stage or request, so the capacity count stays right without leaking the job. `/fragments/plan-usage` returns the same 404 for an explicitly named project the login may not see, and an empty tile for a login with no project of its own. The factory-wide settings pages are limited to factory admins, see Factory admins. The MCP server registry page names the login's own projects alone in its "Used by" card and its held-back-edit confirmation, so neither names a project the login may not see. The confirmation still counts every value the edit deletes, so its button states the full effect, and it reports the count in projects the login may not see without naming them. | | GitHub identity | The factory has no account of its own. A job runs as the project's token or as its requester's own token, see "Account resolution". The account behind a token must be a **Write** collaborator on each target repository, not Admin, so a ruleset's Admin bypass does not apply to it. It should be a bot account, because the factory ignores pull request comments from the account a job runs as and from the project's account, and GitHub does not let an account approve its own pull request. Onboarding a project checks the repository as the onboarding login's own stored token for the forge, not as the bot, through the `GitHubRepos` trait: `GhRepos` runs `gh api` with the token of the `Account` each call is given, and tests pass a fake so none reaches the network. A login with no stored token gets a blocking error that links to `/settings/forges/github`, and the wizard makes no forge call. The dashboard reaches the checks through `Forges`, see "Forge interface". `check_repo` returns errors and warnings. An error blocks onboarding: a repo that is not `owner/name`, one that is missing or not visible to that account, a base branch that does not exist, no push access for that account, and squash merges turned off, which the factory relies on. A warning does not: the account holds Admin, the base branch has no protection or ruleset, the repo has no Actions workflow, and merged branches are not auto-deleted. GitHub answers HTTP 403 for the rules of a branch in a private repository on a free plan. That check then becomes a warning that names GitHub's answer, because it cannot tell whether the branch is protected. A 403 from any other call still means the checks could not run. The onboarding wizard calls them, and picks the checks by the forge selected in its form, see "Salsa and GitLab" for the Salsa ones. | -| Credentials | Only the factory holds the forge tokens that push branches and open pull requests, the project tokens and the personal tokens in its secret store. Workers get no credential for that identity. The one exception is a Copilot worker, which gets the stored Copilot login token in `COPILOT_GITHUB_TOKEN`, see "Copilot auth". That token belongs to a GitHub account on a Copilot plan. The token the device login stores, as observed in step 0, is a `gho_` OAuth token with the scopes `codespace`, `gist`, `read:org`, `read:user`, `repo` and `write:plugin_gateway_connections`. That is wider than Copilot needs, so the account should be one the operator is willing to expose to an agent. It showed no expiry and no refresh token, and the operator revokes it at github.com/settings/applications. A token pasted as the fallback can be a `gho_`, `ghu_` or fine-grained `github_pat_` token. Its permissions and expiry are whatever GitHub issued it with, and a fine-grained token limited to the Copilot Requests permission is the narrowest choice. The factory does not check either. Every Copilot run passes `--disable-builtin-mcps`, so the CLI's built-in GitHub MCP server, which would use that token, is off and a worker gets no GitHub MCP tools. Claude and Codex workers still get no GitHub credential. The factory, not the worker, makes the Renovate pull request reads and writes with the project token: listing the pull requests, reading a pull request's details, a file or an upstream patch, and posting a comment, an approval or a merge. | +| Credentials | Only the factory holds the forge tokens that push branches and open pull requests, the project tokens and the personal tokens in its secret store. Workers get no credential for that identity. The one exception is a Copilot worker, which gets the stored Copilot login token in `COPILOT_GITHUB_TOKEN`, see "Copilot auth". That token belongs to a GitHub account on a Copilot plan. The token the device login stores, as observed in step 0, is a `gho_` OAuth token with the scopes `codespace`, `gist`, `read:org`, `read:user`, `repo` and `write:plugin_gateway_connections`. That is wider than Copilot needs, so the account should be one the operator is willing to expose to an agent. It showed no expiry and no refresh token, and the operator revokes it at github.com/settings/applications. A token pasted as the fallback can be a `gho_`, `ghu_` or fine-grained `github_pat_` token. Its permissions and expiry are whatever GitHub issued it with, and a fine-grained token limited to the Copilot Requests permission is the narrowest choice. The factory does not check either. Every Copilot run passes `--disable-builtin-mcps`, so the CLI's built-in GitHub MCP server, which would use that token, is off and a worker gets no GitHub MCP tools. Claude and Codex workers still get no GitHub credential. The factory, not the worker, makes the Renovate pull request reads and writes with the project token: listing the pull requests, reading a pull request's details, a file or an upstream patch, and posting a comment, an approval or a merge. A run's MCP run token reaches only remote servers. A stdio server needs no credential, so a run with only stdio servers carries no token, see MCP stdio servers. | | Claude auth | The subscription token from `claude setup-token`, held in the factory's encrypted secret store, the same store MCP header values use. An operator sets or replaces it from the settings page, so changing it needs no login to moon. The Claude agent page under Agents, at `/settings/agents/claude` with the heading "Claude", has the "Claude token" field. The token form posts to `/settings/agents/claude/token` and `/settings/agents/claude/token/clear`, and `/settings/claude` redirects to the agent page. It shows only whether a token is stored, never the value and not even in the input's `value` or the page source, the way an MCP header value's field does. A non-empty save replaces the token, after the factory trims surrounding whitespace and a trailing newline; an empty save keeps it; and a separate Clear button removes it. When the secret store is unavailable the field is disabled with a message and Clear still works, so a token stranded by a lost master key can still be removed. A saved token reaches the next worker run with no restart, because the `ClaudeToken` resolver reads it afresh. See "MCP secret storage" for the store. A `ClaudeToken` resolver reads the current token on each use: the stored token when the store is available, or `CLAUDE_CODE_OAUTH_TOKEN` from the environment when it is not, so a lost master key does not stop jobs while the old podman secret still passes the token in. At startup, when the store is available, holds no token, and the env var is set and not empty, the factory imports that value into the store and logs the import without the token, so the move off the podman secret needs no manual step on moon. Once a token is stored the env var is ignored. Workers get the resolved token to run Claude Code. Its usage limits are shared with interactive use. Switch to an API key if the factory hits them often. | | Codex auth | The subscription login `codex login` writes on a ChatGPT Plus or Pro account, the `auth.json` with an access token and a refresh token, held in the factory's encrypted secret store next to the Claude token, see "MCP secret storage". There is no environment-variable import for it, unlike the Claude token: the login enters the factory only through the Codex settings page, `/settings/agents/codex`, two ways. "Sign in with ChatGPT" runs a `codex login --device-auth` container from the worker image and shows the verification URL and one-time code the container prints, see Settings layout. The container's `CODEX_HOME` is a fresh directory under `/codex-login/`, deleted when the login ends. The factory runs in a container and starts this one through the host's podman socket, so the mount source has to be a path that exists on the host; the data directory has the same path on both sides, and the factory container's `/tmp` does not exist on the host. A write-only textarea takes an `auth.json` pasted from a trusted machine, the fallback for when device login fails. The factory accepts a login only when it parses as a JSON object with string values at `tokens.access_token` and `tokens.refresh_token`, and refuses anything else, such as an API key file or a Business access token, with a message that names the missing field and never echoes the input. The page shows only whether a login is stored and when Codex last refreshed it, never the file, a token or the account id. Codex rewrites `auth.json` when it rotates the tokens, so the `CodexLogin` coordinator writes the stored login into a run's config directory before the worker starts, reads it back after, keeps the newer file under a lock, and serialises runs while the login is due for a refresh; see "Running Codex in a worker". A run with no stored login fails before any checkout or container with "no Codex login is set", the way a Claude run fails with "no Claude token is set". The login should belong to the factory alone, because a copy on a laptop shares its refresh token and a refresh on one side can sign the other out. The Business and Enterprise `CODEX_ACCESS_TOKEN`, which would fit the env-var credential like the Claude token, and API keys for either agent, come later. | | Copilot auth | The GitHub token the Copilot CLI runs with, held in the factory's encrypted secret store in its own row, see "MCP secret storage". It enters the factory through the Copilot settings page, `/settings/agents/copilot`, two ways. "Sign in with GitHub" runs `copilot login --device-code` in a worker-image container and shows the URL and code the container prints. The container's `COPILOT_HOME` is a fresh directory under `/copilot-login/`, deleted when the login ends. It holds a `settings.json` with `{"storeTokenPlaintext": true}`, written before the container starts, because the container has no keychain and the CLI otherwise asks before storing the token in plaintext. The CLI then writes the token to `config.json` under `authTokens`, with the same token for each host and account entry. The factory reads the first token there, validates it with `validate_copilot_token` and stores it. A login that stores nothing fails with a reason that says which of four things happened: the CLI wrote no `config.json`, the factory could not read it (with the I/O error), the file held no token, or the token was refused (with the `CopilotTokenError` text). Both the no-file and the no-token reasons list the file names in the config directory, one subdirectory level deep, and the no-token reason also lists the file's top-level keys and the key names under `authTokens`. Names only, never values, and any token-like part of a name, even one joined to other text such as `credential:gho_...`, is shown as `[redacted]`, and a parse error shows its line and column, not the parser's message, which can quote the file. The container's last output, scrubbed of token-like values, follows the reason. The heading reads "The login finished, but the factory could not store a token." when the container exited 0 or left a credential file, which includes a failed save, and "The login did not finish." for a timeout, a spawn or setup failure, and a non-zero exit with no file. The Codex login has the same reasons with `auth.json`, and its heading reads "The login finished, but the factory could not store the login." The prompt line, `To authenticate, visit https://github.com/login/device and enter code 1234-5678`, is read with ANSI color stripped. The container is named `factory-copilot-login` and the factory runs one login at a time. A write-only field takes a pasted `gho_`, `ghu_` or fine-grained `github_pat_` token as the fallback, the way Codex takes a pasted `auth.json`. The page shows only whether a token is stored. The CLI does not refresh the token and does not rewrite it during a run, and the device-login token showed no expiry, so the factory stores it once and does not read it back after a run, see "Copilot CLI facts". A pasted token that expires stops working when it does, and the run then fails with the CLI's authentication error until the operator saves a new one. A run with no stored token fails before any checkout or container with "no Copilot login is set". The login belongs to a GitHub account on a Copilot plan, and the token reaches Copilot workers through `COPILOT_GITHUB_TOKEN`. | @@ -33,12 +33,13 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | MCP server registry | An operator adds MCP servers, remote or stdio, on the MCP servers settings page and edits or deletes one on its own page, see Settings layout. The `mcp_servers` table holds one row per server: a unique `name`, a `kind` of `remote` or `stdio`, and the fields of that kind. A remote server has an `https` `url` and a JSON list of `headers`. A stdio server has a `command` and a JSON list of base `args`, and stores an empty `url` and `[]` for `headers`. The kind is fixed when the server is added, and an edit that would change it is a 400. A database from before stdio servers loads every row as `remote`, because the `kind`, `command` and `args` columns are added with defaults. A name is 1 to 32 characters of `a-z`, `0-9` and `-`, unique, because it keys the run's MCP config and is part of the proxy path. The URL must parse, use `https` and have a host. Each header name is a header a project may fill with a value; it must be a valid HTTP token and not one the factory sets itself or the streamable-HTTP transport owns: `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`. Two header names that differ only in case collapse to the first spelling. A remote server uses streamable HTTP and goes through the MCP proxy. A stdio server is a command the agent starts inside the worker, see MCP stdio servers. The older SSE-only transport is out of scope. A stdio command is trimmed and must be non-empty, at most 256 bytes, with no NUL, line break or `${`. A stdio server has at most 64 base arguments, each at most 4096 bytes with no NUL or `${`, and an argument may hold a line break. The edit form shows such an argument in an ordinary text box with `\`, line feed and carriage return written as `\\`, `\n` and `\r`, and posts it as `arg_escaped`. The server reads those escapes back, so a save keeps the stored value byte for byte without JavaScript and without an index into the stored list. The admin can edit the box or clear it to remove the argument. The command may not hold a line break, and it is checked for one before it is trimmed. An empty argument is dropped, order is kept, and an argument is never trimmed, so spaces, quotes and a lone `$` are stored as typed. The factory refuses `${` because Copilot expands `${NAME}` in the command and arguments of its MCP config and the other agents do not, so one entry then means the same on all three. Editing a stdio server saves at once and keeps every project's settings for it, because it has no stored values to delete. Deleting a server deletes every project's `project_mcp` row and every stored secret for it in one transaction. An edit that changes the URL's origin, its scheme, host or port, deletes every stored secret value for the server, so no dashboard user can repoint a server at their own host and collect another project's keys, and the server's page asks before it saves such an edit, see Settings layout. An edit that changes only the path keeps the values. Removing a header name deletes the stored values for that name alone. A rename is a remove plus an add: the old name's stored values are gone and each project enters a value under the new name. context7 at `https://mcp.context7.com/mcp` is the first server, added by hand through the form. `FACTORY_MCP_CA_FILE` adds root certificates for a server whose certificate is not from a public CA, see MCP connection check, so the `https` rule does not rule out an internal server. | | MCP project settings | Each project has a page per server, see Settings layout, with an enabled switch, a checkbox for each of the five stages, clarify, spec, plan, implement and review, the same five as the project models, and a write-only field for each header the server declares. The `project_mcp` table stores the enabled flag and the five stage flags, keyed by project and server. A project with no row reads off with no stage, so a newly added server and a newly onboarded project both start off. The save handler refuses an enabled server with no stage checked and returns a 400 that names the server. A header field shows only whether a value is stored, "set" or "not set", never the value and not even masked. An empty field leaves the stored value as it is, a typed value replaces it, and a "clear" checkbox deletes it. A header with no stored value is not sent, so a keyless server such as context7 needs none. The page posts to `POST /settings/projects//mcp/`. The handler checks the whole form before any write, so a rejected submit leaves every table as it was. Saving one project's page for a server leaves other projects and other servers alone, and saving the project's own form leaves its MCP settings alone. The scheduler reads the registry and the project's settings on every run, the way it reads the models, so a change reaches a job in flight at its next run. A stdio server's page for a project has the same enabled switch and five stage checkboxes, shows the registry's command and base arguments read-only, and has no header fields, no "Refresh connection" button and no tool list. It adds an "Extra arguments" list for the project, kept in `project_mcp_args`, keyed by project and server, as a JSON array. The list is empty by default. A row is edited one text box per argument with "Add argument" and "Remove" buttons, and posts as a repeated `arg` field, or `arg_escaped` for an argument with a line break, the way the registry form does. The handler reads the pairs in order, because the form's field map would keep only the last `arg`. It checks them with the registry's argument rules: empty arguments are dropped, order is kept, at most 64, each at most 4096 bytes, no NUL and no `${`. A violation is a 400 that names the problem, and the handler writes nothing, not the list, the enabled flag or the stages. A run of the project starts the command, the base arguments and then the project's extra arguments, in that order, and the page shows that command line under the list. A project appends arguments and cannot remove, reorder or replace the base ones. Any collaborator of the project may edit the list. This adds no new power, because the arguments reach only that project's workers and a collaborator already sets the project's checks command, which is arbitrary bash in the same workers. Turning the server off keeps the list, saving it leaves other projects and servers alone, and the pipeline panels' switches, which write only the enabled flag and stages, leave it as it is. A posted `arg` for a remote server is ignored. Deleting the server or removing the project deletes the list. Settings can be saved now. Runs start stdio servers only once worker support lands in a later change, and the scheduler then reads the list on every run, so a change reaches a job at its next run. | | MCP header-name editing | The settings page edits a server's header names in one text box per name, on the add form and each server's edit form, not a textarea of names. An "Add header" button appends an empty row and each row has a "Remove" button, both run by an inline script. The boxes post a repeated `header` field that the add and edit handlers trim, dropping an empty row, so the form works without JavaScript too: the add form starts with one empty box, an edit form shows one box per stored name plus one empty box, you add one name per save and clear a box to drop its name. Each box's `pattern` allows only the HTTP token characters `mcp::normalize_headers` accepts, so a pasted `Authorization: x` is refused in the browser before the server validates it again, see MCP server registry for the validation and the propagation of an add, remove, rename or URL origin change to every project's stored values. A browser compiles a `pattern` as a RegExp with the `v` flag, where `-` and `|` are syntax inside a `[...]` class and must be escaped (as `\-` and `\|`), and an invalid pattern is silently ignored, so both the header-name and the server-name patterns escape them. Only the name goes in the box; the value is per project and encrypted, which the hints state, see MCP secret storage. The base arguments of a stdio server use the same row editor: one text box per argument, "Add argument" and "Remove" buttons run by the same inline script, and a repeated `arg` field. An argument is not trimmed, because a space is part of it, and the server drops an empty one. The add form shows three empty argument boxes so it works without JavaScript. The add form has a kind choice, radio buttons for `remote` and `stdio`, and CSS `:has(input[value=stdio]:checked)` shows the fields of the checked kind, so no JavaScript is needed for it. The add form's URL box is not `required`, because the browser would block a stdio submit on that hidden field, and the server validates it. | -| MCP proxy | The factory runs an HTTP proxy for MCP traffic on its own listener, `FACTORY_PROXY_LISTEN`, which the Quadlet unit sets to `0.0.0.0:8081`, separate from the dashboard on `127.0.0.1:8080`. The factory container and its workers share the `factory` podman network, which `install.sh` creates, so a worker reaches the proxy by the factory's container name at `FACTORY_PROXY_URL` (`http://factory:8081`), while the dashboard port, published only to the host loopback, stays out of a worker's reach. For each agent run with at least one active server the scheduler issues a run token through `RunTokens`: 256 random bits held only in the factory's memory, scoped to the job and the servers active for the run's stage. The scheduler revokes the token when the worker exits, whether the run succeeded, failed or was cancelled, and a factory restart drops every token. The worker gets `claude --mcp-config` with one `http` entry per active server, each pointing at `http://factory:8081/mcp/` and carrying `Authorization: Bearer ` as its only header. A run with no active server gets no MCP flags, so its arguments are unchanged, and check runs and every non-agent container get no config and no token. The proxy answers 401 to a missing, unknown or revoked token and 403 to a server outside the token's scope. For an authorized request it drops the worker's `Authorization` header, adds the project's stored headers, and forwards the method, path suffix, query, body and the protocol headers, `Content-Type`, `Accept`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`, to the server's URL. It streams a `text/event-stream` response without buffering it, except the event that answers a filtered `tools/list`, see MCP tool toggles, and supports the POST, GET and DELETE that streamable HTTP uses. It follows no redirect, so a 3xx cannot carry the headers to another host and is returned to the worker as it is. It uses a 10-second connect timeout and no total timeout, so a streaming response may stay open for the length of the run. The credential stays out of the worker because the worker runs with `bypassPermissions`: it could otherwise read the value from its config, arguments or environment, and a prompt injection in a repository or an MCP response could make it print or send the key. The proxy keeps the value on the factory side, so the worker holds only a run token the proxy swaps for the real headers. The proxy also reports each `tools/call` it forwards, which the factory records as an `mcp-tool-call` row, see Job MCP tool calls. The proxy's client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, the same list the connection check uses. Unset, it trusts the built-in roots alone. A stdio server bypasses the proxy: it gets no run token and no entry that points at the proxy, and `StoreUpstreams::resolve` returns `None` for it, see MCP stdio servers. | -| MCP unavailable servers | An enabled server that is unreachable when a run starts does not fail the run. The run goes on without the server's tools, as Claude Code does. Two paths report it. The runner reads the `mcp_servers` list in the stream-json `system`/`init` line and warns about each active server whose status is not `connected`. The proxy warns when it cannot reach the server, a connection times out, or the server answers 5xx. The scheduler also warns about a server it skipped because a stored header value would not decrypt, so a broken credential never lands in a worker's config. All three funnel through `McpWarnings`, which dedupes per run so a server is warned at most once, and writes the warning through `Store::record_mcp_unavailable`: a factory line to the job log that names the server and the reason, and an `mcp-unavailable` row in `job_events` with `: ` in its `detail`, written the way `add_cost` writes a cost row, so it changes neither the job's stage nor its turn. The reason names no credential. The job page timeline shows the row as a note under the step the run was in. | +| MCP proxy | The factory runs an HTTP proxy for MCP traffic on its own listener, `FACTORY_PROXY_LISTEN`, which the Quadlet unit sets to `0.0.0.0:8081`, separate from the dashboard on `127.0.0.1:8080`. The factory container and its workers share the `factory` podman network, which `install.sh` creates, so a worker reaches the proxy by the factory's container name at `FACTORY_PROXY_URL` (`http://factory:8081`), while the dashboard port, published only to the host loopback, stays out of a worker's reach. For each agent run with at least one active remote server the scheduler issues a run token through `RunTokens`: 256 random bits held only in the factory's memory, scoped to the job and the remote servers active for the run's stage. The scheduler revokes the token when the worker exits, whether the run succeeded, failed or was cancelled, and a factory restart drops every token. The worker gets `claude --mcp-config` with one `http` entry per active remote server, each pointing at `http://factory:8081/mcp/` and carrying `Authorization: Bearer ` as its only header. A run with no active server gets no MCP flags, so its arguments are unchanged, and a run with only stdio servers gets no token, and check runs and every non-agent container get no config and no token. The proxy answers 401 to a missing, unknown or revoked token and 403 to a server outside the token's scope. For an authorized request it drops the worker's `Authorization` header, adds the project's stored headers, and forwards the method, path suffix, query, body and the protocol headers, `Content-Type`, `Accept`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`, to the server's URL. It streams a `text/event-stream` response without buffering it, except the event that answers a filtered `tools/list`, see MCP tool toggles, and supports the POST, GET and DELETE that streamable HTTP uses. It follows no redirect, so a 3xx cannot carry the headers to another host and is returned to the worker as it is. It uses a 10-second connect timeout and no total timeout, so a streaming response may stay open for the length of the run. The credential stays out of the worker because the worker runs with `bypassPermissions`: it could otherwise read the value from its config, arguments or environment, and a prompt injection in a repository or an MCP response could make it print or send the key. The proxy keeps the value on the factory side, so the worker holds only a run token the proxy swaps for the real headers. The proxy also reports each `tools/call` it forwards, which the factory records as an `mcp-tool-call` row, see Job MCP tool calls. The proxy's client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, the same list the connection check uses. Unset, it trusts the built-in roots alone. A stdio server bypasses the proxy: it gets no run token and no entry that points at the proxy, and `StoreUpstreams::resolve` returns `None` for it, see MCP stdio servers. | +| MCP unavailable servers | An enabled server that is unreachable when a run starts does not fail the run. The run goes on without the server's tools, as Claude Code does. Two paths report it. The runner reads the `mcp_servers` list in the stream-json `system`/`init` line and warns about each active server whose status is not `connected`. The proxy warns when it cannot reach the server, a connection times out, or the server answers 5xx. The scheduler also warns about a server it skipped because a stored header value would not decrypt, so a broken credential never lands in a worker's config. All three funnel through `McpWarnings`, which dedupes per run so a server is warned at most once, and writes the warning through `Store::record_mcp_unavailable`: a factory line to the job log that names the server and the reason, and an `mcp-unavailable` row in `job_events` with `: ` in its `detail`, written the way `add_cost` writes a cost row, so it changes neither the job's stage nor its turn. The reason names no credential. The job page timeline shows the row as a note under the step the run was in. A stdio server that fails to start is reported the same way and does not fail the run. Claude reports it in the same `init` line, with a status of `failed`. Copilot's SDK types define `session.mcp_server_status_changed` and `session.mcp_servers_loaded` events whose server status can be `failed`, and the parser maps a failed server in either to the warning, ahead of its ephemeral-event skip, because both are marked ephemeral. The reason is the status only, because the CLI's error text can quote the command's output. No authenticated Copilot run has shown that the CLI writes these events to `--output-format json`, so the manual check on moon confirms it. Codex 0.165.0 writes nothing to `exec --json` or stderr for a stdio server whose command does not exist, so a Codex run gets no warning for a stdio server that fails to start, and the agent finds out when its tools are missing. | | MCP connection check | A project's page for a server has a "Refresh connection" button that tests the server with that project's saved header values and refreshes the project's list of its tools, see MCP tool toggles. It posts to `POST /settings/projects//mcp//check` through htmx, which swaps the returned HTML fragment into a result area, so the page does not reload and unsaved input survives. The handler resolves the saved URL and the project's saved values through `StoreUpstreams`, the same resolver the proxy uses, so the check and a real run send the same headers. It ignores any form field posted with the request, so an unsaved value typed into the page is never sent, and the hint says to save first to check new ones. An unknown project or server gives 404. The check sends one JSON-RPC `initialize` POST, whose `clientInfo` carries the name `factory` and the crate version because the MCP schema requires both and a strict server such as Composio's rejects a request without `version`, with `Content-Type: application/json` and `Accept: application/json, text/event-stream` plus the project's values, follows no redirect like the proxy, uses the proxy's 10-second connect timeout, a 15-second total timeout, and reads at most 1 MiB of the body. Success is a 2xx reply, JSON or SSE, whose `result` carries a `protocolVersion`. The result names the server and version when the reply gives them. A 2xx reply with a JSON-RPC `error` shows the error's code and message, cut to 300 characters, with every header value the check sent replaced by `[redacted]`, since a server may echo the request. On success it sends a best-effort `DELETE` with any `Mcp-Session-Id` to end the session. The result messages cover a reachable MCP server, an unreachable host, a timeout, a 401 or 403 that points to the project's header values, another 3xx, 4xx or 5xx with a 3xx `Location`, a 2xx JSON-RPC error, and a 2xx that is not an MCP reply. A declared header with no stored value is named in the result, and the check runs without it. No header value reaches the fragment, a log line or an error. The result is not stored: reloading the page clears it. The HTTP part sits behind the `McpChecker` trait, held by the dashboard the way it holds `RepoChecker`, so a test uses a fake and the real `HttpMcpChecker` is tested against a local `http://` server. The "Add server" button runs no check, because the header values belong to projects and the add form has none; the per-project check is the one the requester chose. The client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, and the proxy's client trusts the same list. reqwest uses its own bundled roots, so `SSL_CERT_FILE` has no effect, and a server with a self-signed or internal CA certificate could not pass the check. The browser tests' stub MCP server needs this, and so does an operator's internal server. A file that is unreadable or holds no certificate stops the factory at startup, so a typo does not leave a server silently untrusted. Unset, the trusted roots are unchanged. A stdio server runs inside the worker, so the check cannot reach it. `check_mcp_server` answers a stdio server with a 400 and runs nothing. A stdio server has no connection check. It runs inside the worker, so the factory has nothing to reach, and the route answers a stdio server with a 400 and runs nothing. A check would need a throwaway container that starts the command and lists its tools, which is a follow-up. | -| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. Registering a stdio server is the first step. Runs do not carry one yet, and a project has no switch for it, so it does nothing until the later steps that pass it to the agents. | +| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. When a stdio server is active for a run's project and stage, the scheduler passes its name, command and arguments to the runner in `McpConfig`, and each backend writes the entry its CLI reads. The arguments are the registry's base arguments followed by the project's extra arguments, read on every run. The proxy part of `McpConfig`, the URL and the run token, is set only when a remote server is active, so a run with only stdio servers issues no run token and passes no `FACTORY_MCP_TOKEN`. A stdio run adds no `--volume`, `--env` or `--network` flag to `podman run`. The entry shapes, the startup timeouts and the `${` rule are in each agent's section: "Running Claude Code in a worker", "Running Codex in a worker" and "Copilot CLI facts". A stdio server that fails to start does not fail the run, see MCP unavailable servers, and its tool calls are read from the agent's output, see Job MCP tool calls. | +| MCP stdio isolation | A stdio server is shared as a registry entry and nothing else. It is a child process of the agent, in the container of one run of one job, and that container is started with `--rm`, so the server dies with it. No server process is shared between runs, jobs or projects, and none outlives a run. It sees what the agent sees: the job's checkout at `/work`, the job's own agent config directory, the read-only agents directory and the `/nix` volume. What it writes elsewhere, such as the `npx` cache in `~/.npm`, a `uvx` cache or a browser profile, lives in the container's own filesystem and is deleted with the container. The factory adds no shared cache volume and no mount for it. It uses no run token and no stored secret, so it has no credential that could leak to another project. A project runs a server only after one of its own collaborators enables it, and the project's extra arguments, the `mcp-tool-call` rows and the warnings are stored per project or per job. Only an admin changes the command and base arguments, and the server's page lists the projects that use it, so the admin sees who an edit reaches. One resource is shared: the `/nix` volume that every worker of every project mounts read-write through `FACTORY_WORKER_VOLUMES`. Store paths are content-addressed and agents already fill it with `nix shell nixpkgs#...`. Any other volume an operator adds to `FACTORY_WORKER_VOLUMES` is shared the same way. The factory does not harden or split that volume per project. | | MCP tool toggles | A project can turn off single tools of an MCP server it uses. Every tool is on by default, so the factory stores the tools that are off, and a project with none off behaves as before. The setting is per project and server and applies to all five stages, without a per-stage grid. A tool a server adds later starts on. The settings page marks it "new" so an operator sees it. The `project_mcp_tools` table holds the last tool list per project and server, keyed by project, server and tool name, with the tool's description, an `offered` flag, a `disabled` flag and the number of the refresh that first saw it. `project_mcp_tool_refreshes` counts each project and server's refreshes, so a tool is "new" when the latest refresh first saw it and is not the first one. The list is per project because a server may offer different tools for different credentials. "Refresh connection" fills the table, see MCP connection check: after a successful `initialize` it sends `notifications/initialized` and pages through `tools/list` by its cursor with the negotiated `MCP-Protocol-Version` and the `Mcp-Session-Id`. The same 15-second total timeout covers the whole exchange, and each reply is read up to 1 MiB. Only a complete list replaces the stored one. A tool missing from it keeps its row with `offered` cleared, so a turned-off tool stays off if the server offers it again, and the page lists it as "no longer offered". A failed list keeps the old rows and the result says the tools could not be listed. The refresh route returns the page's refresh area, the button, the result and the tool list, and htmx replaces that area, found from the button with `closest .mcp-refresh`. The swap drops unsaved changes to that list's checkboxes, and the hint says so. The list sits on the project's page for the server as one checkbox per stored tool, checked when on, with its description. Each shown tool posts a hidden `mcp..shown.` field and, when checked, `mcp..tool.`. A server name has no `.`, so the handler splits the tool name off after the prefix. The save handler turns off the shown tools left unchecked and turns on the checked ones. It leaves a tool the form did not show as it is, so a refresh between render and save turns nothing off by accident. The proxy enforces the setting, because a worker with `bypassPermissions` and a run token could call a tool with `curl` that a Claude Code flag only hid from the model. `StoreUpstreams` returns the server's turned-off tool names with its headers, read on each request, so a change reaches a run in flight at its next request. For a POST, the proxy parses the body it already buffers as JSON-RPC, rejecting duplicate keys so it and the server cannot read two different tool names. A `tools/call` whose `params.name` is off gets a JSON-RPC error that names the tool as turned off for the project, with the request's `id`, and the proxy forwards nothing. A batch array holding such a call gets a 403 and nothing is forwarded. When the server has a tool turned off, a POST body that does not parse gets a 400 rather than being forwarded. A `tools/list` reply is buffered up to 4 MiB and the turned-off tools are removed from `result.tools`, in a JSON body or in the SSE event carrying the response, with other SSE events passed through as they are. A reply over the cap or one that does not parse is relayed unchanged, and the call block still applies. A stream resumed by `Last-Event-ID` may replay an unfiltered list, and the call block applies there too. Every other request and response streams as before. Each blocked call goes through `McpWarnings`, deduped per run, server and tool, and `Store` writes a factory line to the job log and an `mcp-tool-blocked` row in `job_events` with `: ` in its `detail`, which the job page timeline shows as a note under the step. Deleting a server deletes its tool rows with its `project_mcp` rows. A rename loses them like the stored values. An edit that changes the URL's origin clears `offered` on every row and keeps each `disabled` flag until the next refresh. A stdio server has no tool toggles. The proxy is what enforces them, a stdio server bypasses it, and listing its tools needs the same throwaway container as the connection check. A toggle could then only hide a tool from the model, not block it. Both are a follow-up. | -| Job MCP tool calls | Every MCP call a job makes passes through the proxy, so the proxy records it. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | +| Job MCP tool calls | Every MCP call a job makes passes through the proxy, so the proxy records it. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | | Approval gates | Spec, plan and publish. Each project has its own gates, in a `project_gates` table in SQLite with one row per project and a column per gate. The factory-wide gates in the stored settings are the defaults: onboarding a project copies them into its row, and a later change to a default leaves existing projects alone. Spec and plan are on in the code default, publish is off. The settings page edits the defaults on the Default gates page and a project's gates on its pipeline, see Settings layout. A job copies its project's gates when it is created, so a later settings change does not touch existing jobs. Everything after the last gate runs without stopping, apart from questions the agent asks. The state machine stops at a gate only when the job has it. A job with the publish gate stops before the first push of each planned pull request and waits for approval. Later pushes to the same pull request, such as fixes for CI or review comments, are not gated. Gates were one global setting before. A one-time migration at startup gives every project with no `project_gates` row the current global gates, the way `Store::migrate_global_auto_merge` moved auto-merge, so each project keeps its earlier behaviour. You merge on GitHub, unless the project's auto-merge setting is on: then the factory squash-merges a pull request once every check passed and no review comment waits for the agent. Auto-merge is per project, see Project settings. A pull request with no checks reported yet is not merged, so a push is never merged before GitHub starts its CI. | | Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling and Renovate. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page: Claude's is `/settings/agents/claude` and Codex's is `/settings/agents/codex` and Copilot's is `/settings/agents/copilot`. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a selectable radio. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is five radio buttons. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. A model field that holds one of the previous agent's suggestions is cleared to "CLI default", because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent. Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". | | Renovate retry limits | Two factory-wide limits govern the reruns of failed CI on a Renovate pull request. Automatic reruns is how many times the factory reruns failed CI on one head commit before it asks an agent, default 3. Total reruns is how many reruns one head commit gets before the factory comments and stops triage, default 7. They live in the settings JSON row as `renovate_auto_reruns` and `renovate_total_reruns`, so a factory that never saved them reads 3 and 7. They are factory-wide because the factory has one CI flakiness profile for its Renovate pull requests, and a per-project value would only add a field to forget. The page is `/settings/renovate`, in the Factory group and admin-only like the other Factory pages. A save is refused with a message and nothing stored when a value is not a whole number, when total is less than 1, or when automatic is greater than total. Automatic 0 is valid and sends the first failure to the agent. The Renovate triage reads them on every watch, so a change will apply to jobs already in flight and need no restart. | @@ -128,9 +129,10 @@ moon.local (rootless podman, user moon) image: Claude Code, Codex, git, nix, unzip mounts: job workspace, the run's agent config directory, shared /nix store volume, cargo cache per project, factory agents directory (read-only) network: the shared factory podman network, to reach the MCP proxy but not the dashboard - env: the run's agent credential and, when a server is active, the per-run MCP token + env: the run's agent credential and, when a remote server is active, the per-run MCP token Claude gets its token through --env, see Claude auth; Codex reads its auth.json from the mounted config directory, see Codex auth both agents get the MCP token through --env with no value and a proxy config written by the backend + stdio MCP servers: a child process of the agent inside the worker, started from the command in the agent's MCP config; it bypasses the proxy, carries no token and dies with the container ``` GitHub cannot reach `moon.local`, so the factory polls GitHub with `gh api` about once a minute instead of receiving webhooks. @@ -180,6 +182,7 @@ This is the Claude agent's implementation of the `AgentBackend` interface, see " - The factory's rules come in through `--plugin-dir` (skills and agents) and `--settings` (hooks). A headless run in an untrusted folder ignores a repository's `extraKnownMarketplaces` without any message, so the factory must not depend on the target repository's plugin settings. - The target repository's own `CLAUDE.md` and project skills still load. maestro has its own `no-comments` and `open-pr` skills, so the factory's plugin namespaces its versions as `factory:no-comments` and `factory:open-pr`. - Claude Code keeps an MCP server's tools behind its tool-search step and loads a tool's schema only when the model searches for it, such as `mcp____`. A run never reaches a tool nothing names, so a run with at least one active server gets a prompt paragraph that lists the servers and tells the agent to load their tools before it starts, see "Prompt boundary". A gateway server adds a second layer: its listed tools only search for and run other tools, and the app tools appear only when the agent searches by use case. The paragraph points the agent at the server's search tool for that. The paragraph is the same for Codex, where the load step costs nothing because Codex lists a server's own tools up front. A gateway's catalog stays hidden for Codex too, so the gateway sentences apply there. +- A stdio MCP server is a `"": {"type": "stdio", "command": "...", "args": [...]}` entry in `--mcp-config`, next to the `http` entries. Claude starts the process itself in `/work`. Its startup timeout is `MCP_TIMEOUT`, which defaults to 30 seconds. A run with a stdio server sets `"env": {"MCP_TIMEOUT": "120000"}` in the `--settings` JSON, which takes effect and needs no podman `--env`: checked on Claude Code 2.1.330, a server that never answered was marked `failed` in the `init` line after about 6 seconds with `MCP_TIMEOUT=1500` in settings and after about 33 seconds without it. A run with no stdio server passes the same `--settings` as before. A server that cannot start shows as `"status":"failed"` in the `init` line, which the runner reports as an unavailable server. Claude does not expand `${NAME}` in a command or argument, but the factory refuses `${` anyway, see MCP server registry. - Claude Code hooks run under whatever shell the container has, without the nix devShell. Write hook scripts for plain bash and test them that way. ## Running Codex in a worker @@ -194,7 +197,7 @@ The worker image carries Codex next to Claude Code, and the `AgentBackend` in `f - **Sessions.** Codex assigns the session id itself and reports it in `thread.started`, so the factory learns it from the stream and cannot pass it in advance the way it passes Claude's `--session-id`. The parser turns `thread.started` into an item the scheduler stores in the `sessions` table's agent-session-id column as soon as the line arrives, so a run that dies after that line can still resume. A resumed run uses `codex exec resume ` when the id is stored and a rollout file for it exists under `CODEX_HOME/sessions`, and otherwise starts a new session. Claude leaves the column empty, because it uses the factory's UUID. - **Structured output.** Each run ends with `--output-schema`, which makes the final agent message match the schema. OpenAI's strict rules want every property in `required` and `additionalProperties: false` on every object, so a stage that may leave a field out marks it nullable and the outcome resolution reads a `null` as absent. The text of the last `agent_message` item goes through the same outcome resolution as Claude's `structured_output`, so a missing output or an outcome the stage does not allow fails the run the same way. - **Config.** `CODEX_HOME=/codex` inside the worker, mounted from the job's `codex` directory on the host. The backend writes a `config.toml` there that sets `cli_auth_credentials_store = "file"` and no `project_doc_fallback_filenames`, so Codex keeps the login in the file rather than an OS keyring and reads a repository's `AGENTS.md` rather than its `CLAUDE.md`. -- **MCP.** Each active server becomes `-c mcp_servers..url="/mcp/"` and `-c mcp_servers..bearer_token_env_var="FACTORY_MCP_TOKEN"`, and the run token reaches the container through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the `podman` arguments and the log. A run with no active server passes no MCP flags and no token. The proxy, its run tokens, the tool toggles and the `mcp-tool-call` rows work for a Codex run unchanged, because they sit on the factory side. A run with an active server also gets the shared prompt paragraph that names the servers, asks the agent to load their tools first and covers gateway servers, the same paragraph a Claude run gets, see "Prompt boundary". +- **MCP.** Each active server becomes `-c mcp_servers..url="/mcp/"` and `-c mcp_servers..bearer_token_env_var="FACTORY_MCP_TOKEN"`, and the run token reaches the container through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the `podman` arguments and the log. A stdio server becomes `-c mcp_servers..command=""`, `-c mcp_servers..args=[...]` and `-c mcp_servers..startup_timeout_sec=120`, because Codex's default startup timeout is 10 seconds and a first `npx` or `uvx` start downloads the package. Values are TOML basic strings, with the backslash, quote and control characters escaped, so a quote, backslash or space in an argument arrives unchanged. The pinned 0.165.0 binary accepted these overrides, including an argument that held `"`, `\` and a space. A run with only stdio servers passes no `FACTORY_MCP_TOKEN`. A run with no active server passes no MCP flags and no token. The proxy, its run tokens, the tool toggles and the `mcp-tool-call` rows work for a Codex run unchanged, because they sit on the factory side. A run with an active server also gets the shared prompt paragraph that names the servers, asks the agent to load their tools first and covers gateway servers, the same paragraph a Claude run gets, see "Prompt boundary". - **Parser.** The Codex parser turns the JSON Lines into the same `AgentItem`s as Claude's stream parser. Agent messages, command executions with their exit code, file changes, MCP tool calls and errors become log lines in the same style, such as `tool mcp____` for an MCP call. It sums the `usage` of every `turn.completed` line for the cost estimate, see Job cost. A `turn.failed` carries its reason under `error.message` and a top-level `error` under `message`, and either without a final agent message fails the run with "the Codex run failed: ". A login Codex rejected mid-run surfaces as that failure, and the job page's Retry runs the task again once a new login is stored. A non-fatal item `error`, such as a startup warning, is a log line and does not fail the run. - The image installs one pinned Codex release, set by the `CODEX_VERSION` build arg (`0.165.0`). It downloads the `codex-package-x86_64-unknown-linux-musl` tarball from the `rust-v` GitHub release, unpacks it to `/opt/codex` and links `/opt/codex/bin/codex` as `/usr/local/bin/codex`. The build fails if `codex --version` does not report that version or `codex-code-mode-host` is missing. moon is x86_64, so the image pins that one asset rather than detect the architecture. @@ -242,7 +245,7 @@ The worker image carries the GitHub Copilot CLI next to Claude Code and Codex, a - **Credential.** The CLI does not refresh the token, and the device-login token showed no expiry (see the "Copilot CLI facts" gate result), so the backend uses `Credential::Env("COPILOT_GITHUB_TOKEN")`, not the read-back file Codex needs. The factory sets the token in the podman process environment and the worker gets it with `--env COPILOT_GITHUB_TOKEN` and no value, so the token never appears in the `podman` arguments, the job log or an error message. `COPILOT_GITHUB_TOKEN` is first in the CLI's lookup order, so the stored login wins over any token baked into the image. - **Config.** `COPILOT_HOME=/copilot` inside the worker, mounted from the job's `copilot` directory on the host. It keeps `session-state//` for a resumed run. It holds no login: the device flow's scratch directory is deleted once the token is in the secret store, and a worker gets the token through `COPILOT_GITHUB_TOKEN`. - **Structured output.** The CLI has no output-schema flag, so the backend asks for the JSON in the prompt: the `PromptStyle` carries an instruction that tells the agent to end with one final message of only the JSON, gives the reason (text outside the JSON fails the run) and names where a summary goes (the schema's fields, or nowhere), and `prompt.rs` appends the stage's schema (see "Prompt boundary"). When the message ends with a fenced code block, the parser reads that last block as the JSON, whatever text comes before it. Text after the closing fence, or a message with no fenced block that is not JSON itself, fails the run, and the parser searches nowhere else. Copilot agents write a summary before the JSON despite the instruction, which already said "no sentence before it", so the prompt now gives the reason and a place for the summary. Failing a finished run over that wastes the run. A repair turn that asks for the JSON again was rejected because it costs another premium request, and brace-matching unfenced JSON is out of scope. The text of the last assistant message goes through the same outcome resolution as Claude's `structured_output`, so a missing output, invalid JSON, or an outcome the stage does not allow fails the run the way Codex's does. -- **MCP.** The built-in `github-mcp-server` would reach GitHub with the login token, so every run passes `--disable-builtin-mcps` and a worker gets no GitHub MCP tools. Each active factory server becomes one `http` entry in `--additional-mcp-config`, pointed at `/mcp/` with `Authorization: Bearer ${FACTORY_MCP_TOKEN}` and `"tools": ["*"]`. The CLI expands `${FACTORY_MCP_TOKEN}` from the environment, where the run sets it through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the arguments and the log. A run with no active server passes no MCP flag. The run with an active server also gets the shared prompt paragraph that names the servers, asks for their tools to be loaded and covers gateway servers, the same one Claude and Codex get, see "Prompt boundary". +- **MCP.** The built-in `github-mcp-server` would reach GitHub with the login token, so every run passes `--disable-builtin-mcps` and a worker gets no GitHub MCP tools. Each active factory server becomes one `http` entry in `--additional-mcp-config`, pointed at `/mcp/` with `Authorization: Bearer ${FACTORY_MCP_TOKEN}` and `"tools": ["*"]`. The CLI expands `${FACTORY_MCP_TOKEN}` from the environment, where the run sets it through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the arguments and the log. A stdio server becomes `"": {"type": "local", "command": "...", "args": [...], "tools": ["*"]}` in the same config. The SDK types, `MCPStdioServerConfig` in `copilot-sdk/types.d.ts`, accept `"local"` or `"stdio"` for `type`, and the factory writes `local`. Copilot has no startup timeout setting: the `timeout` field is in milliseconds for tool calls to the server, so a stdio server keeps the CLI's own startup behaviour. Copilot expands `${NAME}` in a command or argument from its environment and the other agents do not, which is why the registry and a project's extra arguments refuse `${`. A run with only stdio servers passes no `FACTORY_MCP_TOKEN`. A run with no active server passes no MCP flag. The run with an active server also gets the shared prompt paragraph that names the servers, asks for their tools to be loaded and covers gateway servers, the same one Claude and Codex get, see "Prompt boundary". - **Review method.** Every run passes `--plugin-dir /factory-agents`, whether or not the factory mounts its own agents directory, because the image bakes a copy there. The flag always resolves, so the review-method wording names the skill rather than a path. The reviewed repository's own skills still load alongside it. - **Parser.** The parser turns the JSON Lines into the same `AgentItem`s as the Claude and Codex parsers, skipping the `ephemeral` events such as the streaming deltas. A non-ephemeral `assistant.message` logs its `data.content`. Only a message with an empty `toolRequests` list is a final answer and resolves the result, so a run that fails after a message written before a tool call ends on the failure and not on that message; among final answers the last wins. `tool.execution_start` logs one line: an MCP call as `tool mcp____`, a shell command (the event's `shellToolInfo`) as an `exec` line, and a built-in file edit as an `edit` line; other tools, such as a read, log nothing, the way Codex drops a read step. A failed `tool.execution_complete` notes the failure without failing the run. `session.warning` logs its message. Copilot reports no fatal-error event in the stream and puts the human cause of a failed run on stderr, so the parser keys a failure off a non-zero `result.exitCode` with "the Copilot run failed: the CLI exited with code ", used only when no final message arrived. The result records `cost_usd: None`. `session.usage_checkpoint` logs the premium requests, the AI credits and the input, cache read, cache write and output token counts the CLI reports, and the final `result` line logs its premium request count. The backend's `start_log` hook writes one line before the run reads any output, noting that Copilot runs are not counted in the job cost, so a run killed before any output still carries it. None of this makes an estimate. - The image creates `/copilot`, owned by the worker user, the way it creates `/claude` and `/codex`. The Copilot backend mounts the job's `copilot` directory there as `COPILOT_HOME`. @@ -283,6 +286,8 @@ Confirmed from the pinned CLI's own SDK types, `copilot-sdk/generated/session-ev - A tool call emits `tool.execution_start` then `tool.execution_complete`. The start event carries `data.toolName`, `data.arguments`, and, for an MCP tool, `data.mcpServerName` and `data.mcpToolName`; a shell tool (`bash`) carries `data.shellToolInfo.displayCommand`. The complete event carries `data.success` and, on failure, `data.error.message`, keyed to the start by `data.toolCallId` but with no tool name of its own. The parser logs the start as an `exec`, `edit` or `mcp____` line and notes a failed complete; see "Running Copilot in a worker". - `session.warning` carries `data.message`. The parser logs it. +- `session.mcp_server_status_changed` carries `data.serverName`, `data.status` (`connected`, `failed`, `needs-auth`, `pending`, `disabled`, `stopped` or `not_configured`) and, for a failure, `data.error`. `session.mcp_servers_loaded` lists `data.servers` with the same `name`, `status` and `error`. Both are marked `ephemeral`. The parser turns a `failed` status in either into an unavailable-server warning, without the error text. These are the SDK's shapes, not a captured run, so the manual check confirms that the `-p --output-format json` stream carries them. +- A stdio server entry is `{"type":"local","command":"…","args":[…],"tools":["*"]}`. `type` is `"local" | "stdio"` in the SDK types, `timeout` is the tool-call timeout in milliseconds, and there is no startup timeout field. The binary accepts `--additional-mcp-config` with such an entry, but an unauthenticated run stops before it starts the server. - These shapes are the SDK's, not a captured run. The manual check on moon (acceptance criterion 10) is the first authenticated tool-using run; if a shape differs there, the parser and this section are corrected then. ## Layout From 4197f9a04ffa00d1e7cd3c0e8d59f0a40d512aac Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:30:01 +0000 Subject: [PATCH 2/3] crates: pass stdio MCP config through a file Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-runner/src/claude.rs | 24 +++++--- crates/factory-runner/src/codex.rs | 45 ++++++++------- crates/factory-runner/src/copilot.rs | 15 ++++- crates/factory-runner/src/worker.rs | 8 +++ crates/factory-runner/tests/codex.rs | 70 +++++++++++++++--------- crates/factory-runner/tests/copilot.rs | 38 +++++++++++-- crates/factory-runner/tests/runner.rs | 50 +++++++++++++++-- crates/factory-server/src/scheduler.rs | 2 - crates/factory-server/tests/scheduler.rs | 1 - docs/design.md | 12 ++-- 10 files changed, 191 insertions(+), 74 deletions(-) diff --git a/crates/factory-runner/src/claude.rs b/crates/factory-runner/src/claude.rs index b602dbcb..5eed6960 100644 --- a/crates/factory-runner/src/claude.rs +++ b/crates/factory-runner/src/claude.rs @@ -23,6 +23,7 @@ use crate::worker::{ /// The Claude Code config directory inside the worker, mounted from the job's /// `claude` directory on the host. It keeps the session files `--resume` reads. const CONFIG_DIR: &str = "/claude"; +const MCP_CONFIG_FILE: &str = "factory-mcp.json"; /// Settings for every Claude run. Claude Code adds a `Co-Authored-By` trailer /// to commits and a footer to pull request descriptions unless `attribution` @@ -67,6 +68,13 @@ impl AgentBackend for ClaudeAgent { "claude" } + fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> { + match run.mcp.as_ref().filter(|mcp| mcp.has_stdio()) { + Some(mcp) => fs::write(run.config_dir.join(MCP_CONFIG_FILE), mcp_config(mcp)), + None => Ok(()), + } + } + fn session_for(&self, host_config_dir: &Path, id: &str) -> SessionRun { let transcript = format!("{id}.jsonl"); if contains_file(&host_config_dir.join("projects"), &transcript) { @@ -114,10 +122,15 @@ impl AgentBackend for ClaudeAgent { ); // One `http` entry per active MCP server, pointed at the proxy with the // run token. A run with no active server adds nothing, so its arguments - // match a run from before MCP. + // match a run from before MCP. A run with a stdio server reads the config + // from a file, since its arguments can outgrow one argv element. if let Some(mcp) = run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) { claude.push("--mcp-config".into()); - claude.push(mcp_config(mcp)); + if mcp.has_stdio() { + claude.push(format!("{CONFIG_DIR}/{MCP_CONFIG_FILE}")); + } else { + claude.push(mcp_config(mcp)); + } } claude.into_iter().map(OsString::from).collect() } @@ -156,12 +169,7 @@ impl AgentBackend for ClaudeAgent { /// first start of a package runner downloads the package and the default is 30 /// seconds. Settings carry it, so the container gets no `--env` for it. fn settings(mcp: Option<&McpConfig>) -> String { - let has_stdio = mcp.is_some_and(|mcp| { - mcp.servers - .iter() - .any(|server| matches!(server, McpServerEntry::Stdio { .. })) - }); - if has_stdio { + if mcp.is_some_and(McpConfig::has_stdio) { serde_json::json!({ "attribution": { "commit": "", "pr": "", "sessionUrl": false }, "env": { "MCP_TIMEOUT": (STDIO_STARTUP_TIMEOUT_SECS * 1000).to_string() }, diff --git a/crates/factory-runner/src/codex.rs b/crates/factory-runner/src/codex.rs index 0cccdc7e..89cd8c0c 100644 --- a/crates/factory-runner/src/codex.rs +++ b/crates/factory-runner/src/codex.rs @@ -104,7 +104,25 @@ impl AgentBackend for CodexAgent { } fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> { - fs::write(run.config_dir.join(CONFIG_FILE), CONFIG_TOML)?; + let mut config = CONFIG_TOML.to_owned(); + for entry in run.mcp.iter().flat_map(|mcp| &mcp.servers) { + if let McpServerEntry::Stdio { + name, + command, + args, + } = entry + { + // Codex's startup timeout defaults to 10 seconds, too short for + // a first download. + let _ = write!( + config, + "\n[mcp_servers.{name}]\ncommand = {}\nargs = {}\nstartup_timeout_sec = {STDIO_STARTUP_TIMEOUT_SECS}\n", + toml_string(command), + toml_array(args) + ); + } + } + fs::write(run.config_dir.join(CONFIG_FILE), config)?; fs::write( run.config_dir.join(SCHEMA_FILE), run.expect.strict_schema().to_string(), @@ -155,9 +173,8 @@ impl AgentBackend for CodexAgent { )); // A remote MCP server is pointed at the proxy. The run token is passed // by name, not value, so it stays out of the arguments; the proxy swaps - // it for the project's stored headers. A stdio server is a command with - // arguments and a startup timeout, since Codex's default is 10 seconds. - // A run with no active server adds nothing. + // it for the project's stored headers. A run with no active server adds + // nothing. if let Some(mcp) = run.mcp.as_ref() { for entry in &mcp.servers { match entry { @@ -175,23 +192,9 @@ impl AgentBackend for CodexAgent { "mcp_servers.{server}.bearer_token_env_var=\"{MCP_TOKEN_ENV}\"" )); } - McpServerEntry::Stdio { - name, - command, - args, - } => { - codex.push("-c".into()); - codex.push(format!( - "mcp_servers.{name}.command={}", - toml_string(command) - )); - codex.push("-c".into()); - codex.push(format!("mcp_servers.{name}.args={}", toml_array(args))); - codex.push("-c".into()); - codex.push(format!( - "mcp_servers.{name}.startup_timeout_sec={STDIO_STARTUP_TIMEOUT_SECS}" - )); - } + // Stdio entries live in config.toml, since their arguments + // can outgrow one argv element. + McpServerEntry::Stdio { .. } => {} } } } diff --git a/crates/factory-runner/src/copilot.rs b/crates/factory-runner/src/copilot.rs index 3c6c6332..42e80f8a 100644 --- a/crates/factory-runner/src/copilot.rs +++ b/crates/factory-runner/src/copilot.rs @@ -16,6 +16,7 @@ //! the stream, so the parser keys a failure off a non-zero `result.exitCode`. use std::ffi::OsString; +use std::fs; use std::path::Path; use factory_core::Agent; @@ -33,6 +34,7 @@ use crate::worker::{ /// keeps `session-state//` for a resumed run, next to the login the device /// flow stores. const CONFIG_DIR: &str = "/copilot"; +const MCP_CONFIG_FILE: &str = "factory-mcp.json"; /// The environment variable Copilot reads its GitHub token from. It is first in /// the CLI's lookup order, so the factory's stored login wins over any token in @@ -96,6 +98,13 @@ impl AgentBackend for CopilotAgent { "copilot" } + fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> { + match run.mcp.as_ref().filter(|mcp| mcp.has_stdio()) { + Some(mcp) => fs::write(run.config_dir.join(MCP_CONFIG_FILE), mcp_config(mcp)), + None => Ok(()), + } + } + fn session_for(&self, host_config_dir: &Path, id: &str) -> SessionRun { if host_config_dir.join("session-state").join(id).is_dir() { SessionRun::Resume(id.to_owned()) @@ -153,7 +162,11 @@ impl AgentBackend for CopilotAgent { ); if let Some(mcp) = run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) { copilot.push("--additional-mcp-config".into()); - copilot.push(mcp_config(mcp)); + if mcp.has_stdio() { + copilot.push(format!("@{CONFIG_DIR}/{MCP_CONFIG_FILE}")); + } else { + copilot.push(mcp_config(mcp)); + } } // The image bakes the review skills at `/factory-agents` whether or not // the factory mounts its own copy there, so the flag always resolves and diff --git a/crates/factory-runner/src/worker.rs b/crates/factory-runner/src/worker.rs index 490d5601..8f4afbc7 100644 --- a/crates/factory-runner/src/worker.rs +++ b/crates/factory-runner/src/worker.rs @@ -88,6 +88,14 @@ impl McpConfig { pub fn names(&self) -> Vec<&str> { self.servers.iter().map(McpServerEntry::name).collect() } + + /// Whether any active server is a stdio server. + #[must_use] + pub fn has_stdio(&self) -> bool { + self.servers + .iter() + .any(|server| matches!(server, McpServerEntry::Stdio { .. })) + } } /// One active MCP server in a run's config. diff --git a/crates/factory-runner/tests/codex.rs b/crates/factory-runner/tests/codex.rs index a84db34a..797f66b7 100644 --- a/crates/factory-runner/tests/codex.rs +++ b/crates/factory-runner/tests/codex.rs @@ -198,9 +198,15 @@ fn stdio_entry() -> McpServerEntry { } } +fn written_config(run: &WorkerRun, dir: &Path) -> toml::Value { + backend(Agent::Codex).unwrap().prepare(run).unwrap(); + toml::from_str(&fs::read_to_string(dir.join("codex/config.toml")).unwrap()).unwrap() +} + #[test] -fn a_stdio_server_becomes_toml_overrides_with_a_startup_timeout_and_no_token() { +fn a_stdio_server_goes_into_config_toml_with_a_startup_timeout_and_no_token() { let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("codex")).unwrap(); let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); let plain = codex_args(&run); run.mcp = Some(McpConfig { @@ -209,38 +215,48 @@ fn a_stdio_server_becomes_toml_overrides_with_a_startup_timeout_and_no_token() { }); let args = codex_args(&run); - let overrides: Vec<&String> = args - .iter() - .filter(|arg| arg.starts_with("mcp_servers.")) - .collect(); + assert_eq!(args, plain); // The quote, backslash and space in the second argument are escaped, so // TOML reads them back unchanged. + let config = written_config(&run, dir.path()); + let server = &config["mcp_servers"]["pw"]; + assert_eq!(server["command"].as_str(), Some("playwright-mcp")); assert_eq!( - overrides, - [ - r#"mcp_servers.pw.command="playwright-mcp""#, - r#"mcp_servers.pw.args=["--no-sandbox","a \"b\\c\" d"]"#, - "mcp_servers.pw.startup_timeout_sec=120", - ] + server["args"], + toml::Value::try_from(["--no-sandbox", "a \"b\\c\" d"]).unwrap() ); - let value: toml::Value = toml::from_str(&format!( - "args = {}", - overrides[1].strip_prefix("mcp_servers.pw.args=").unwrap() - )) - .unwrap(); - assert_eq!(value["args"][1].as_str(), Some("a \"b\\c\" d")); - + assert_eq!(server["startup_timeout_sec"].as_integer(), Some(120)); + assert_eq!(config["cli_auth_credentials_store"].as_str(), Some("file")); assert!(!env_names(&args).contains(&"FACTORY_MCP_TOKEN"), "{args:?}"); - assert!(!args.iter().any(|arg| arg.contains("factory:8081"))); - // No container flag is added: only the config overrides differ. - let flags = |args: &[String]| args.iter().filter(|a| a.starts_with("--")).count(); - assert_eq!(flags(&args), flags(&plain)); - assert_eq!(env_names(&args), env_names(&plain)); +} + +#[test] +fn stdio_arguments_too_big_for_one_argv_element_go_through_config_toml() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("codex")).unwrap(); + let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); + let big: Vec = (0..64).map(|i| format!("{i:x<4096}")).collect(); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: big.clone(), + }], + }); + // Linux rejects one argv element of 128 KiB or more. + assert!(codex_args(&run).iter().all(|arg| arg.len() < 128 * 1024)); + let config = written_config(&run, dir.path()); + assert_eq!( + config["mcp_servers"]["pw"]["args"], + toml::Value::try_from(big).unwrap() + ); } #[test] fn a_remote_and_a_stdio_server_share_a_codex_run() { let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("codex")).unwrap(); let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); run.mcp = Some(McpConfig { proxy: Some(McpProxy { @@ -259,9 +275,11 @@ fn a_remote_and_a_stdio_server_share_a_codex_run() { args.iter() .any(|arg| { arg == "mcp_servers.context7.url=\"http://factory:8081/mcp/context7\"" }) ); - assert!( - args.iter() - .any(|arg| arg.starts_with("mcp_servers.pw.command=")) + assert!(!args.iter().any(|arg| arg.starts_with("mcp_servers.pw."))); + let config = written_config(&run, dir.path()); + assert_eq!( + config["mcp_servers"]["pw"]["command"].as_str(), + Some("playwright-mcp") ); assert!(env_names(&args).contains(&"FACTORY_MCP_TOKEN")); } diff --git a/crates/factory-runner/tests/copilot.rs b/crates/factory-runner/tests/copilot.rs index 97b0250c..2551a40a 100644 --- a/crates/factory-runner/tests/copilot.rs +++ b/crates/factory-runner/tests/copilot.rs @@ -206,6 +206,7 @@ fn stdio_entry() -> McpServerEntry { #[test] fn a_stdio_server_becomes_a_local_entry_with_no_token() { let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("copilot")).unwrap(); let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); let plain = copilot_args(&run); run.mcp = Some(McpConfig { @@ -214,8 +215,11 @@ fn a_stdio_server_becomes_a_local_entry_with_no_token() { }); let args = copilot_args(&run); - let config: serde_json::Value = - serde_json::from_str(value_after(&args, "--additional-mcp-config")).unwrap(); + assert_eq!( + value_after(&args, "--additional-mcp-config"), + "@/copilot/factory-mcp.json" + ); + let config = written_config(&run, dir.path()); assert_eq!( config["mcpServers"], serde_json::json!({ "pw": { @@ -230,9 +234,36 @@ fn a_stdio_server_becomes_a_local_entry_with_no_token() { assert_eq!(env_names(&args), env_names(&plain)); } +fn written_config(run: &WorkerRun, dir: &Path) -> serde_json::Value { + backend(Agent::Copilot).unwrap().prepare(run).unwrap(); + serde_json::from_str(&fs::read_to_string(dir.join("copilot/factory-mcp.json")).unwrap()) + .unwrap() +} + +#[test] +fn stdio_arguments_too_big_for_one_argv_element_go_through_the_config_file() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("copilot")).unwrap(); + let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); + let big: Vec = (0..64).map(|i| format!("{i:x<4096}")).collect(); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: big.clone(), + }], + }); + // Linux rejects one argv element of 128 KiB or more. + assert!(copilot_args(&run).iter().all(|arg| arg.len() < 128 * 1024)); + let config = written_config(&run, dir.path()); + assert_eq!(config["mcpServers"]["pw"]["args"], serde_json::json!(big)); +} + #[test] fn a_remote_and_a_stdio_server_share_a_copilot_run() { let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("copilot")).unwrap(); let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); run.mcp = Some(McpConfig { proxy: Some(McpProxy { @@ -247,8 +278,7 @@ fn a_remote_and_a_stdio_server_share_a_copilot_run() { ], }); let args = copilot_args(&run); - let config: serde_json::Value = - serde_json::from_str(value_after(&args, "--additional-mcp-config")).unwrap(); + let config = written_config(&run, dir.path()); assert_eq!(config["mcpServers"]["context7"]["type"], "http"); assert_eq!(config["mcpServers"]["pw"]["type"], "local"); assert!(env_names(&args).contains(&"FACTORY_MCP_TOKEN")); diff --git a/crates/factory-runner/tests/runner.rs b/crates/factory-runner/tests/runner.rs index 6557d331..ccd88a97 100644 --- a/crates/factory-runner/tests/runner.rs +++ b/crates/factory-runner/tests/runner.rs @@ -1007,7 +1007,9 @@ fn stdio_entry() -> McpServerEntry { #[test] fn podman_args_give_a_stdio_server_a_command_entry_and_no_token_or_proxy() { - let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Resume(SESSION.into())); + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("claude")).unwrap(); + let mut run = worker_run(dir.path(), SessionRun::Resume(SESSION.into())); let plain = strings(&podman_args(&WorkerConfig::default(), &run)); run.mcp = Some(McpConfig { proxy: None, @@ -1015,7 +1017,15 @@ fn podman_args_give_a_stdio_server_a_command_entry_and_no_token_or_proxy() { }); let args = strings(&podman_args(&WorkerConfig::default(), &run)); - let config: Value = serde_json::from_str(value_after(&args, "--mcp-config")).unwrap(); + assert_eq!( + value_after(&args, "--mcp-config"), + "/claude/factory-mcp.json" + ); + backend(Agent::Claude).unwrap().prepare(&run).unwrap(); + let config: Value = serde_json::from_str( + &fs::read_to_string(dir.path().join("claude/factory-mcp.json")).unwrap(), + ) + .unwrap(); assert_eq!( config["mcpServers"], json!({ "pw": { @@ -1040,7 +1050,9 @@ fn podman_args_give_a_stdio_server_a_command_entry_and_no_token_or_proxy() { #[test] fn podman_args_carry_a_remote_and_a_stdio_server_together() { - let mut run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("claude")).unwrap(); + let mut run = worker_run(dir.path(), SessionRun::Start(SESSION.into())); run.mcp = Some(McpConfig { proxy: Some(McpProxy { url: "http://factory:8081".into(), @@ -1053,8 +1065,11 @@ fn podman_args_carry_a_remote_and_a_stdio_server_together() { stdio_entry(), ], }); - let args = strings(&podman_args(&WorkerConfig::default(), &run)); - let config: Value = serde_json::from_str(value_after(&args, "--mcp-config")).unwrap(); + backend(Agent::Claude).unwrap().prepare(&run).unwrap(); + let config: Value = serde_json::from_str( + &fs::read_to_string(dir.path().join("claude/factory-mcp.json")).unwrap(), + ) + .unwrap(); assert_eq!( config["mcpServers"]["context7"], json!({ @@ -1066,6 +1081,31 @@ fn podman_args_carry_a_remote_and_a_stdio_server_together() { assert_eq!(config["mcpServers"]["pw"]["type"], "stdio"); } +#[test] +fn stdio_arguments_too_big_for_one_argv_element_go_through_the_config_file() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("claude")).unwrap(); + let mut run = worker_run(dir.path(), SessionRun::Start(SESSION.into())); + let big: Vec = (0..64).map(|i| format!("{i:x<4096}")).collect(); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![McpServerEntry::Stdio { + name: "pw".into(), + command: "playwright-mcp".into(), + args: big.clone(), + }], + }); + let args = podman_args(&WorkerConfig::default(), &run); + // Linux rejects one argv element of 128 KiB or more. + assert!(args.iter().all(|arg| arg.len() < 128 * 1024)); + backend(Agent::Claude).unwrap().prepare(&run).unwrap(); + let config: Value = serde_json::from_str( + &fs::read_to_string(dir.path().join("claude/factory-mcp.json")).unwrap(), + ) + .unwrap(); + assert_eq!(config["mcpServers"]["pw"]["args"], json!(big)); +} + #[test] fn a_run_without_a_stdio_server_keeps_the_settings_it_had() { let run = worker_run(Path::new("/jobs/7"), SessionRun::Start(SESSION.into())); diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 7e316eed..fce6fea5 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -1382,8 +1382,6 @@ impl Scheduler { .filter(|server| matches!(server, ActiveServer::Remote(_))) .map(|server| server.name().to_owned()) .collect(); - // Only a remote server goes through the proxy, so a run with stdio - // servers alone gets no token. let proxy = (!remote.is_empty()).then(|| McpProxy { url: self.mcp.proxy_url.clone(), token: self.mcp.tokens.issue(job_id, project, &remote), diff --git a/crates/factory-server/tests/scheduler.rs b/crates/factory-server/tests/scheduler.rs index 737cf78e..32d8924b 100644 --- a/crates/factory-server/tests/scheduler.rs +++ b/crates/factory-server/tests/scheduler.rs @@ -209,7 +209,6 @@ impl Executor for FakeExecutor { session(id); } log(LogLine::Text("Reading the repository.".into())); - // The tool names the test queued, logged the way the agent's output is. let tools = self.tool_calls.lock().unwrap().pop_front(); for name in tools.into_iter().flatten() { log(LogLine::Tool { diff --git a/docs/design.md b/docs/design.md index a2a4a83b..2d46eed0 100644 --- a/docs/design.md +++ b/docs/design.md @@ -31,15 +31,15 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | Copilot auth | The GitHub token the Copilot CLI runs with, held in the factory's encrypted secret store in its own row, see "MCP secret storage". It enters the factory through the Copilot settings page, `/settings/agents/copilot`, two ways. "Sign in with GitHub" runs `copilot login --device-code` in a worker-image container and shows the URL and code the container prints. The container's `COPILOT_HOME` is a fresh directory under `/copilot-login/`, deleted when the login ends. It holds a `settings.json` with `{"storeTokenPlaintext": true}`, written before the container starts, because the container has no keychain and the CLI otherwise asks before storing the token in plaintext. The CLI then writes the token to `config.json` under `authTokens`, with the same token for each host and account entry. The factory reads the first token there, validates it with `validate_copilot_token` and stores it. A login that stores nothing fails with a reason that says which of four things happened: the CLI wrote no `config.json`, the factory could not read it (with the I/O error), the file held no token, or the token was refused (with the `CopilotTokenError` text). Both the no-file and the no-token reasons list the file names in the config directory, one subdirectory level deep, and the no-token reason also lists the file's top-level keys and the key names under `authTokens`. Names only, never values, and any token-like part of a name, even one joined to other text such as `credential:gho_...`, is shown as `[redacted]`, and a parse error shows its line and column, not the parser's message, which can quote the file. The container's last output, scrubbed of token-like values, follows the reason. The heading reads "The login finished, but the factory could not store a token." when the container exited 0 or left a credential file, which includes a failed save, and "The login did not finish." for a timeout, a spawn or setup failure, and a non-zero exit with no file. The Codex login has the same reasons with `auth.json`, and its heading reads "The login finished, but the factory could not store the login." The prompt line, `To authenticate, visit https://github.com/login/device and enter code 1234-5678`, is read with ANSI color stripped. The container is named `factory-copilot-login` and the factory runs one login at a time. A write-only field takes a pasted `gho_`, `ghu_` or fine-grained `github_pat_` token as the fallback, the way Codex takes a pasted `auth.json`. The page shows only whether a token is stored. The CLI does not refresh the token and does not rewrite it during a run, and the device-login token showed no expiry, so the factory stores it once and does not read it back after a run, see "Copilot CLI facts". A pasted token that expires stops working when it does, and the run then fails with the CLI's authentication error until the operator saves a new one. A run with no stored token fails before any checkout or container with "no Copilot login is set". The login belongs to a GitHub account on a Copilot plan, and the token reaches Copilot workers through `COPILOT_GITHUB_TOKEN`. | | MCP secret storage | Per-project header values for MCP servers are credentials, so the factory encrypts them at rest. Each value is sealed with XChaCha20-Poly1305 under a random per-value nonce, with the project, server and header name bound in as associated data, so a ciphertext copied into another row fails to decrypt. The ciphertext lives in the `secrets` table, keyed by project, server and header, separate from the server and per-project settings tables, so a later user system can add an owner column in a migration. The master key is 32 random bytes in the `factory-master-key` podman secret, held outside the database. `deploy/install.sh` generates it when it is missing, the same way it creates `gh-token`, so no step is manual, and it never regenerates the key on a later run. The Quadlet unit passes the key to the factory container alone. Workers never get it, so a stolen worker cannot read a credential, and a stolen database file or backup leaks nothing without the key. The key is excluded from database backups. Losing it makes every stored value unreadable, and each one must be entered again. When the key is missing or malformed the factory still starts and reports the secret store as unavailable, rather than refusing to run. Secret access goes through the `SecretStore` trait, with put, get and delete for MCP header values, get, set and clear for the account-wide Claude token, and the same three for the account-wide Codex login and for the account-wide Copilot token. The local encrypted backend is its only implementation now, and each row records its backend, so an external manager such as Vault can be added later without a schema change for existing rows. The Claude subscription token from `claude setup-token` is stored here too, sealed the same way but in one reserved row of the `secrets` table whose `server` is empty, which no MCP server name can be. So `delete from secrets where server = ?` for any MCP server, including one named `claude`, never touches it, and deleting or renaming such a server leaves the token in place. Its ciphertext binds a fixed domain tag rather than a project, server and header, so a ciphertext moved between the token row and an MCP header row fails to decrypt in either direction. The Codex `auth.json` a ChatGPT Plus or Pro `codex login` writes sits in a second reserved row the same way, with header `codex-auth` and its own domain tag, so it survives an MCP server named `codex` and a ciphertext moved between the Codex row, the Claude token row and an MCP header row fails to decrypt in every direction. The factory accepts a login only when it parses as a JSON object with string values at `tokens.access_token` and `tokens.refresh_token`; anything else is refused with a message that names the missing field and never echoes the input. The Copilot token sits in a third reserved row the same way, with header `copilot-token` and its own domain tag, so it survives an MCP server named `copilot` and a ciphertext moved between any two of the reserved rows or an MCP header row fails to decrypt. `validate_copilot_token` trims the input and accepts `gho_`, `ghu_` and `github_pat_` tokens. It refuses a classic `ghp_` token with a message that says to use a fine-grained token with the Copilot Requests permission, and refuses anything else with a message that names the problem. No message echoes the input. The `CodexLogin` coordinator resolves this row for a run, serialises runs while the login is due for a refresh and writes a refreshed login back under a lock (see "Running Codex in a worker"). An operator enters or replaces the login on the Codex settings page, `/settings/agents/codex` (see Settings layout). Forge tokens, see "Forge tokens", sit in rows of their own too. Their `server` is empty, so deleting an MCP server never matches them, and each ciphertext binds the tag `factory:forge-token:v1` plus the length-framed owner kind, key and forge, so a ciphertext moved between two forge token rows, or into an MCP header row or a reserved row, fails to decrypt. `put_forge_token`, `forge_token` and `delete_forge_token` take a `ForgeTokenOwner`. Delete works with the store unavailable. | | MCP server registry | An operator adds MCP servers, remote or stdio, on the MCP servers settings page and edits or deletes one on its own page, see Settings layout. The `mcp_servers` table holds one row per server: a unique `name`, a `kind` of `remote` or `stdio`, and the fields of that kind. A remote server has an `https` `url` and a JSON list of `headers`. A stdio server has a `command` and a JSON list of base `args`, and stores an empty `url` and `[]` for `headers`. The kind is fixed when the server is added, and an edit that would change it is a 400. A database from before stdio servers loads every row as `remote`, because the `kind`, `command` and `args` columns are added with defaults. A name is 1 to 32 characters of `a-z`, `0-9` and `-`, unique, because it keys the run's MCP config and is part of the proxy path. The URL must parse, use `https` and have a host. Each header name is a header a project may fill with a value; it must be a valid HTTP token and not one the factory sets itself or the streamable-HTTP transport owns: `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`. Two header names that differ only in case collapse to the first spelling. A remote server uses streamable HTTP and goes through the MCP proxy. A stdio server is a command the agent starts inside the worker, see MCP stdio servers. The older SSE-only transport is out of scope. A stdio command is trimmed and must be non-empty, at most 256 bytes, with no NUL, line break or `${`. A stdio server has at most 64 base arguments, each at most 4096 bytes with no NUL or `${`, and an argument may hold a line break. The edit form shows such an argument in an ordinary text box with `\`, line feed and carriage return written as `\\`, `\n` and `\r`, and posts it as `arg_escaped`. The server reads those escapes back, so a save keeps the stored value byte for byte without JavaScript and without an index into the stored list. The admin can edit the box or clear it to remove the argument. The command may not hold a line break, and it is checked for one before it is trimmed. An empty argument is dropped, order is kept, and an argument is never trimmed, so spaces, quotes and a lone `$` are stored as typed. The factory refuses `${` because Copilot expands `${NAME}` in the command and arguments of its MCP config and the other agents do not, so one entry then means the same on all three. Editing a stdio server saves at once and keeps every project's settings for it, because it has no stored values to delete. Deleting a server deletes every project's `project_mcp` row and every stored secret for it in one transaction. An edit that changes the URL's origin, its scheme, host or port, deletes every stored secret value for the server, so no dashboard user can repoint a server at their own host and collect another project's keys, and the server's page asks before it saves such an edit, see Settings layout. An edit that changes only the path keeps the values. Removing a header name deletes the stored values for that name alone. A rename is a remove plus an add: the old name's stored values are gone and each project enters a value under the new name. context7 at `https://mcp.context7.com/mcp` is the first server, added by hand through the form. `FACTORY_MCP_CA_FILE` adds root certificates for a server whose certificate is not from a public CA, see MCP connection check, so the `https` rule does not rule out an internal server. | -| MCP project settings | Each project has a page per server, see Settings layout, with an enabled switch, a checkbox for each of the five stages, clarify, spec, plan, implement and review, the same five as the project models, and a write-only field for each header the server declares. The `project_mcp` table stores the enabled flag and the five stage flags, keyed by project and server. A project with no row reads off with no stage, so a newly added server and a newly onboarded project both start off. The save handler refuses an enabled server with no stage checked and returns a 400 that names the server. A header field shows only whether a value is stored, "set" or "not set", never the value and not even masked. An empty field leaves the stored value as it is, a typed value replaces it, and a "clear" checkbox deletes it. A header with no stored value is not sent, so a keyless server such as context7 needs none. The page posts to `POST /settings/projects//mcp/`. The handler checks the whole form before any write, so a rejected submit leaves every table as it was. Saving one project's page for a server leaves other projects and other servers alone, and saving the project's own form leaves its MCP settings alone. The scheduler reads the registry and the project's settings on every run, the way it reads the models, so a change reaches a job in flight at its next run. A stdio server's page for a project has the same enabled switch and five stage checkboxes, shows the registry's command and base arguments read-only, and has no header fields, no "Refresh connection" button and no tool list. It adds an "Extra arguments" list for the project, kept in `project_mcp_args`, keyed by project and server, as a JSON array. The list is empty by default. A row is edited one text box per argument with "Add argument" and "Remove" buttons, and posts as a repeated `arg` field, or `arg_escaped` for an argument with a line break, the way the registry form does. The handler reads the pairs in order, because the form's field map would keep only the last `arg`. It checks them with the registry's argument rules: empty arguments are dropped, order is kept, at most 64, each at most 4096 bytes, no NUL and no `${`. A violation is a 400 that names the problem, and the handler writes nothing, not the list, the enabled flag or the stages. A run of the project starts the command, the base arguments and then the project's extra arguments, in that order, and the page shows that command line under the list. A project appends arguments and cannot remove, reorder or replace the base ones. Any collaborator of the project may edit the list. This adds no new power, because the arguments reach only that project's workers and a collaborator already sets the project's checks command, which is arbitrary bash in the same workers. Turning the server off keeps the list, saving it leaves other projects and servers alone, and the pipeline panels' switches, which write only the enabled flag and stages, leave it as it is. A posted `arg` for a remote server is ignored. Deleting the server or removing the project deletes the list. Settings can be saved now. Runs start stdio servers only once worker support lands in a later change, and the scheduler then reads the list on every run, so a change reaches a job at its next run. | +| MCP project settings | Each project has a page per server, see Settings layout, with an enabled switch, a checkbox for each of the five stages, clarify, spec, plan, implement and review, the same five as the project models, and a write-only field for each header the server declares. The `project_mcp` table stores the enabled flag and the five stage flags, keyed by project and server. A project with no row reads off with no stage, so a newly added server and a newly onboarded project both start off. The save handler refuses an enabled server with no stage checked and returns a 400 that names the server. A header field shows only whether a value is stored, "set" or "not set", never the value and not even masked. An empty field leaves the stored value as it is, a typed value replaces it, and a "clear" checkbox deletes it. A header with no stored value is not sent, so a keyless server such as context7 needs none. The page posts to `POST /settings/projects//mcp/`. The handler checks the whole form before any write, so a rejected submit leaves every table as it was. Saving one project's page for a server leaves other projects and other servers alone, and saving the project's own form leaves its MCP settings alone. The scheduler reads the registry and the project's settings on every run, the way it reads the models, so a change reaches a job in flight at its next run. A stdio server's page for a project has the same enabled switch and five stage checkboxes, shows the registry's command and base arguments read-only, and has no header fields, no "Refresh connection" button and no tool list. It adds an "Extra arguments" list for the project, kept in `project_mcp_args`, keyed by project and server, as a JSON array. The list is empty by default. A row is edited one text box per argument with "Add argument" and "Remove" buttons, and posts as a repeated `arg` field, or `arg_escaped` for an argument with a line break, the way the registry form does. The handler reads the pairs in order, because the form's field map would keep only the last `arg`. It checks them with the registry's argument rules: empty arguments are dropped, order is kept, at most 64, each at most 4096 bytes, no NUL and no `${`. A violation is a 400 that names the problem, and the handler writes nothing, not the list, the enabled flag or the stages. A run of the project starts the command, the base arguments and then the project's extra arguments, in that order, and the page shows that command line under the list. A project appends arguments and cannot remove, reorder or replace the base ones. Any collaborator of the project may edit the list. This adds no new power, because the arguments reach only that project's workers and a collaborator already sets the project's checks command, which is arbitrary bash in the same workers. Turning the server off keeps the list, saving it leaves other projects and servers alone, and the pipeline panels' switches, which write only the enabled flag and stages, leave it as it is. A posted `arg` for a remote server is ignored. Deleting the server or removing the project deletes the list. The scheduler reads the list on every run, so a change reaches a job at its next run, and the worker starts the server as a child of the agent. | | MCP header-name editing | The settings page edits a server's header names in one text box per name, on the add form and each server's edit form, not a textarea of names. An "Add header" button appends an empty row and each row has a "Remove" button, both run by an inline script. The boxes post a repeated `header` field that the add and edit handlers trim, dropping an empty row, so the form works without JavaScript too: the add form starts with one empty box, an edit form shows one box per stored name plus one empty box, you add one name per save and clear a box to drop its name. Each box's `pattern` allows only the HTTP token characters `mcp::normalize_headers` accepts, so a pasted `Authorization: x` is refused in the browser before the server validates it again, see MCP server registry for the validation and the propagation of an add, remove, rename or URL origin change to every project's stored values. A browser compiles a `pattern` as a RegExp with the `v` flag, where `-` and `|` are syntax inside a `[...]` class and must be escaped (as `\-` and `\|`), and an invalid pattern is silently ignored, so both the header-name and the server-name patterns escape them. Only the name goes in the box; the value is per project and encrypted, which the hints state, see MCP secret storage. The base arguments of a stdio server use the same row editor: one text box per argument, "Add argument" and "Remove" buttons run by the same inline script, and a repeated `arg` field. An argument is not trimmed, because a space is part of it, and the server drops an empty one. The add form shows three empty argument boxes so it works without JavaScript. The add form has a kind choice, radio buttons for `remote` and `stdio`, and CSS `:has(input[value=stdio]:checked)` shows the fields of the checked kind, so no JavaScript is needed for it. The add form's URL box is not `required`, because the browser would block a stdio submit on that hidden field, and the server validates it. | | MCP proxy | The factory runs an HTTP proxy for MCP traffic on its own listener, `FACTORY_PROXY_LISTEN`, which the Quadlet unit sets to `0.0.0.0:8081`, separate from the dashboard on `127.0.0.1:8080`. The factory container and its workers share the `factory` podman network, which `install.sh` creates, so a worker reaches the proxy by the factory's container name at `FACTORY_PROXY_URL` (`http://factory:8081`), while the dashboard port, published only to the host loopback, stays out of a worker's reach. For each agent run with at least one active remote server the scheduler issues a run token through `RunTokens`: 256 random bits held only in the factory's memory, scoped to the job and the remote servers active for the run's stage. The scheduler revokes the token when the worker exits, whether the run succeeded, failed or was cancelled, and a factory restart drops every token. The worker gets `claude --mcp-config` with one `http` entry per active remote server, each pointing at `http://factory:8081/mcp/` and carrying `Authorization: Bearer ` as its only header. A run with no active server gets no MCP flags, so its arguments are unchanged, and a run with only stdio servers gets no token, and check runs and every non-agent container get no config and no token. The proxy answers 401 to a missing, unknown or revoked token and 403 to a server outside the token's scope. For an authorized request it drops the worker's `Authorization` header, adds the project's stored headers, and forwards the method, path suffix, query, body and the protocol headers, `Content-Type`, `Accept`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`, to the server's URL. It streams a `text/event-stream` response without buffering it, except the event that answers a filtered `tools/list`, see MCP tool toggles, and supports the POST, GET and DELETE that streamable HTTP uses. It follows no redirect, so a 3xx cannot carry the headers to another host and is returned to the worker as it is. It uses a 10-second connect timeout and no total timeout, so a streaming response may stay open for the length of the run. The credential stays out of the worker because the worker runs with `bypassPermissions`: it could otherwise read the value from its config, arguments or environment, and a prompt injection in a repository or an MCP response could make it print or send the key. The proxy keeps the value on the factory side, so the worker holds only a run token the proxy swaps for the real headers. The proxy also reports each `tools/call` it forwards, which the factory records as an `mcp-tool-call` row, see Job MCP tool calls. The proxy's client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, the same list the connection check uses. Unset, it trusts the built-in roots alone. A stdio server bypasses the proxy: it gets no run token and no entry that points at the proxy, and `StoreUpstreams::resolve` returns `None` for it, see MCP stdio servers. | | MCP unavailable servers | An enabled server that is unreachable when a run starts does not fail the run. The run goes on without the server's tools, as Claude Code does. Two paths report it. The runner reads the `mcp_servers` list in the stream-json `system`/`init` line and warns about each active server whose status is not `connected`. The proxy warns when it cannot reach the server, a connection times out, or the server answers 5xx. The scheduler also warns about a server it skipped because a stored header value would not decrypt, so a broken credential never lands in a worker's config. All three funnel through `McpWarnings`, which dedupes per run so a server is warned at most once, and writes the warning through `Store::record_mcp_unavailable`: a factory line to the job log that names the server and the reason, and an `mcp-unavailable` row in `job_events` with `: ` in its `detail`, written the way `add_cost` writes a cost row, so it changes neither the job's stage nor its turn. The reason names no credential. The job page timeline shows the row as a note under the step the run was in. A stdio server that fails to start is reported the same way and does not fail the run. Claude reports it in the same `init` line, with a status of `failed`. Copilot's SDK types define `session.mcp_server_status_changed` and `session.mcp_servers_loaded` events whose server status can be `failed`, and the parser maps a failed server in either to the warning, ahead of its ephemeral-event skip, because both are marked ephemeral. The reason is the status only, because the CLI's error text can quote the command's output. No authenticated Copilot run has shown that the CLI writes these events to `--output-format json`, so the manual check on moon confirms it. Codex 0.165.0 writes nothing to `exec --json` or stderr for a stdio server whose command does not exist, so a Codex run gets no warning for a stdio server that fails to start, and the agent finds out when its tools are missing. | | MCP connection check | A project's page for a server has a "Refresh connection" button that tests the server with that project's saved header values and refreshes the project's list of its tools, see MCP tool toggles. It posts to `POST /settings/projects//mcp//check` through htmx, which swaps the returned HTML fragment into a result area, so the page does not reload and unsaved input survives. The handler resolves the saved URL and the project's saved values through `StoreUpstreams`, the same resolver the proxy uses, so the check and a real run send the same headers. It ignores any form field posted with the request, so an unsaved value typed into the page is never sent, and the hint says to save first to check new ones. An unknown project or server gives 404. The check sends one JSON-RPC `initialize` POST, whose `clientInfo` carries the name `factory` and the crate version because the MCP schema requires both and a strict server such as Composio's rejects a request without `version`, with `Content-Type: application/json` and `Accept: application/json, text/event-stream` plus the project's values, follows no redirect like the proxy, uses the proxy's 10-second connect timeout, a 15-second total timeout, and reads at most 1 MiB of the body. Success is a 2xx reply, JSON or SSE, whose `result` carries a `protocolVersion`. The result names the server and version when the reply gives them. A 2xx reply with a JSON-RPC `error` shows the error's code and message, cut to 300 characters, with every header value the check sent replaced by `[redacted]`, since a server may echo the request. On success it sends a best-effort `DELETE` with any `Mcp-Session-Id` to end the session. The result messages cover a reachable MCP server, an unreachable host, a timeout, a 401 or 403 that points to the project's header values, another 3xx, 4xx or 5xx with a 3xx `Location`, a 2xx JSON-RPC error, and a 2xx that is not an MCP reply. A declared header with no stored value is named in the result, and the check runs without it. No header value reaches the fragment, a log line or an error. The result is not stored: reloading the page clears it. The HTTP part sits behind the `McpChecker` trait, held by the dashboard the way it holds `RepoChecker`, so a test uses a fake and the real `HttpMcpChecker` is tested against a local `http://` server. The "Add server" button runs no check, because the header values belong to projects and the add form has none; the per-project check is the one the requester chose. The client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, and the proxy's client trusts the same list. reqwest uses its own bundled roots, so `SSL_CERT_FILE` has no effect, and a server with a self-signed or internal CA certificate could not pass the check. The browser tests' stub MCP server needs this, and so does an operator's internal server. A file that is unreadable or holds no certificate stops the factory at startup, so a typo does not leave a server silently untrusted. Unset, the trusted roots are unchanged. A stdio server runs inside the worker, so the check cannot reach it. `check_mcp_server` answers a stdio server with a 400 and runs nothing. A stdio server has no connection check. It runs inside the worker, so the factory has nothing to reach, and the route answers a stdio server with a 400 and runs nothing. A check would need a throwaway container that starts the command and lists its tools, which is a follow-up. | -| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. When a stdio server is active for a run's project and stage, the scheduler passes its name, command and arguments to the runner in `McpConfig`, and each backend writes the entry its CLI reads. The arguments are the registry's base arguments followed by the project's extra arguments, read on every run. The proxy part of `McpConfig`, the URL and the run token, is set only when a remote server is active, so a run with only stdio servers issues no run token and passes no `FACTORY_MCP_TOKEN`. A stdio run adds no `--volume`, `--env` or `--network` flag to `podman run`. The entry shapes, the startup timeouts and the `${` rule are in each agent's section: "Running Claude Code in a worker", "Running Codex in a worker" and "Copilot CLI facts". A stdio server that fails to start does not fail the run, see MCP unavailable servers, and its tool calls are read from the agent's output, see Job MCP tool calls. | +| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. When a stdio server is active for a run's project and stage, the scheduler passes its name, command and arguments to the runner in `McpConfig`, and each backend writes the entry its CLI reads. The arguments are the registry's base arguments followed by the project's extra arguments, read on every run. The proxy part of `McpConfig`, the URL and the run token, is set only when a remote server is active, so a run with only stdio servers issues no run token and passes no `FACTORY_MCP_TOKEN`. A stdio run adds no `--volume`, `--env` or `--network` flag to `podman run`. The entries go into a file in the job's agent config directory, which the run already mounts, and not into the command line, because Linux rejects one argument of 128 KiB or more and 64 base and extra arguments of 4096 bytes can exceed that. Claude reads `--mcp-config /claude/factory-mcp.json`, Copilot reads `--additional-mcp-config @/copilot/factory-mcp.json`, and Codex reads the stdio tables in its `config.toml`. The runner writes the file in `AgentBackend::prepare`, before the container starts. The entry shapes, the startup timeouts and the `${` rule are in each agent's section: "Running Claude Code in a worker", "Running Codex in a worker" and "Copilot CLI facts". A stdio server that fails to start does not fail the run, see MCP unavailable servers, and its tool calls are read from the agent's output, see Job MCP tool calls. | | MCP stdio isolation | A stdio server is shared as a registry entry and nothing else. It is a child process of the agent, in the container of one run of one job, and that container is started with `--rm`, so the server dies with it. No server process is shared between runs, jobs or projects, and none outlives a run. It sees what the agent sees: the job's checkout at `/work`, the job's own agent config directory, the read-only agents directory and the `/nix` volume. What it writes elsewhere, such as the `npx` cache in `~/.npm`, a `uvx` cache or a browser profile, lives in the container's own filesystem and is deleted with the container. The factory adds no shared cache volume and no mount for it. It uses no run token and no stored secret, so it has no credential that could leak to another project. A project runs a server only after one of its own collaborators enables it, and the project's extra arguments, the `mcp-tool-call` rows and the warnings are stored per project or per job. Only an admin changes the command and base arguments, and the server's page lists the projects that use it, so the admin sees who an edit reaches. One resource is shared: the `/nix` volume that every worker of every project mounts read-write through `FACTORY_WORKER_VOLUMES`. Store paths are content-addressed and agents already fill it with `nix shell nixpkgs#...`. Any other volume an operator adds to `FACTORY_WORKER_VOLUMES` is shared the same way. The factory does not harden or split that volume per project. | | MCP tool toggles | A project can turn off single tools of an MCP server it uses. Every tool is on by default, so the factory stores the tools that are off, and a project with none off behaves as before. The setting is per project and server and applies to all five stages, without a per-stage grid. A tool a server adds later starts on. The settings page marks it "new" so an operator sees it. The `project_mcp_tools` table holds the last tool list per project and server, keyed by project, server and tool name, with the tool's description, an `offered` flag, a `disabled` flag and the number of the refresh that first saw it. `project_mcp_tool_refreshes` counts each project and server's refreshes, so a tool is "new" when the latest refresh first saw it and is not the first one. The list is per project because a server may offer different tools for different credentials. "Refresh connection" fills the table, see MCP connection check: after a successful `initialize` it sends `notifications/initialized` and pages through `tools/list` by its cursor with the negotiated `MCP-Protocol-Version` and the `Mcp-Session-Id`. The same 15-second total timeout covers the whole exchange, and each reply is read up to 1 MiB. Only a complete list replaces the stored one. A tool missing from it keeps its row with `offered` cleared, so a turned-off tool stays off if the server offers it again, and the page lists it as "no longer offered". A failed list keeps the old rows and the result says the tools could not be listed. The refresh route returns the page's refresh area, the button, the result and the tool list, and htmx replaces that area, found from the button with `closest .mcp-refresh`. The swap drops unsaved changes to that list's checkboxes, and the hint says so. The list sits on the project's page for the server as one checkbox per stored tool, checked when on, with its description. Each shown tool posts a hidden `mcp..shown.` field and, when checked, `mcp..tool.`. A server name has no `.`, so the handler splits the tool name off after the prefix. The save handler turns off the shown tools left unchecked and turns on the checked ones. It leaves a tool the form did not show as it is, so a refresh between render and save turns nothing off by accident. The proxy enforces the setting, because a worker with `bypassPermissions` and a run token could call a tool with `curl` that a Claude Code flag only hid from the model. `StoreUpstreams` returns the server's turned-off tool names with its headers, read on each request, so a change reaches a run in flight at its next request. For a POST, the proxy parses the body it already buffers as JSON-RPC, rejecting duplicate keys so it and the server cannot read two different tool names. A `tools/call` whose `params.name` is off gets a JSON-RPC error that names the tool as turned off for the project, with the request's `id`, and the proxy forwards nothing. A batch array holding such a call gets a 403 and nothing is forwarded. When the server has a tool turned off, a POST body that does not parse gets a 400 rather than being forwarded. A `tools/list` reply is buffered up to 4 MiB and the turned-off tools are removed from `result.tools`, in a JSON body or in the SSE event carrying the response, with other SSE events passed through as they are. A reply over the cap or one that does not parse is relayed unchanged, and the call block still applies. A stream resumed by `Last-Event-ID` may replay an unfiltered list, and the call block applies there too. Every other request and response streams as before. Each blocked call goes through `McpWarnings`, deduped per run, server and tool, and `Store` writes a factory line to the job log and an `mcp-tool-blocked` row in `job_events` with `: ` in its `detail`, which the job page timeline shows as a note under the step. Deleting a server deletes its tool rows with its `project_mcp` rows. A rename loses them like the stored values. An edit that changes the URL's origin clears `offered` on every row and keeps each `disabled` flag until the next refresh. A stdio server has no tool toggles. The proxy is what enforces them, a stdio server bypasses it, and listing its tools needs the same throwaway container as the connection check. A toggle could then only hide a tool from the model, not block it. Both are a follow-up. | -| Job MCP tool calls | Every MCP call a job makes passes through the proxy, so the proxy records it. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | +| Job MCP tool calls | The proxy records every call a job makes to a remote server, and the scheduler records every call to a stdio server from the agent's output. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | | Approval gates | Spec, plan and publish. Each project has its own gates, in a `project_gates` table in SQLite with one row per project and a column per gate. The factory-wide gates in the stored settings are the defaults: onboarding a project copies them into its row, and a later change to a default leaves existing projects alone. Spec and plan are on in the code default, publish is off. The settings page edits the defaults on the Default gates page and a project's gates on its pipeline, see Settings layout. A job copies its project's gates when it is created, so a later settings change does not touch existing jobs. Everything after the last gate runs without stopping, apart from questions the agent asks. The state machine stops at a gate only when the job has it. A job with the publish gate stops before the first push of each planned pull request and waits for approval. Later pushes to the same pull request, such as fixes for CI or review comments, are not gated. Gates were one global setting before. A one-time migration at startup gives every project with no `project_gates` row the current global gates, the way `Store::migrate_global_auto_merge` moved auto-merge, so each project keeps its earlier behaviour. You merge on GitHub, unless the project's auto-merge setting is on: then the factory squash-merges a pull request once every check passed and no review comment waits for the agent. Auto-merge is per project, see Project settings. A pull request with no checks reported yet is not merged, so a push is never merged before GitHub starts its CI. | | Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling and Renovate. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page: Claude's is `/settings/agents/claude` and Codex's is `/settings/agents/codex` and Copilot's is `/settings/agents/copilot`. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a selectable radio. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is five radio buttons. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. A model field that holds one of the previous agent's suggestions is cleared to "CLI default", because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent. Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". | | Renovate retry limits | Two factory-wide limits govern the reruns of failed CI on a Renovate pull request. Automatic reruns is how many times the factory reruns failed CI on one head commit before it asks an agent, default 3. Total reruns is how many reruns one head commit gets before the factory comments and stops triage, default 7. They live in the settings JSON row as `renovate_auto_reruns` and `renovate_total_reruns`, so a factory that never saved them reads 3 and 7. They are factory-wide because the factory has one CI flakiness profile for its Renovate pull requests, and a per-project value would only add a field to forget. The page is `/settings/renovate`, in the Factory group and admin-only like the other Factory pages. A save is refused with a message and nothing stored when a value is not a whole number, when total is less than 1, or when automatic is greater than total. Automatic 0 is valid and sends the first failure to the agent. The Renovate triage reads them on every watch, so a change will apply to jobs already in flight and need no restart. | @@ -182,7 +182,7 @@ This is the Claude agent's implementation of the `AgentBackend` interface, see " - The factory's rules come in through `--plugin-dir` (skills and agents) and `--settings` (hooks). A headless run in an untrusted folder ignores a repository's `extraKnownMarketplaces` without any message, so the factory must not depend on the target repository's plugin settings. - The target repository's own `CLAUDE.md` and project skills still load. maestro has its own `no-comments` and `open-pr` skills, so the factory's plugin namespaces its versions as `factory:no-comments` and `factory:open-pr`. - Claude Code keeps an MCP server's tools behind its tool-search step and loads a tool's schema only when the model searches for it, such as `mcp____`. A run never reaches a tool nothing names, so a run with at least one active server gets a prompt paragraph that lists the servers and tells the agent to load their tools before it starts, see "Prompt boundary". A gateway server adds a second layer: its listed tools only search for and run other tools, and the app tools appear only when the agent searches by use case. The paragraph points the agent at the server's search tool for that. The paragraph is the same for Codex, where the load step costs nothing because Codex lists a server's own tools up front. A gateway's catalog stays hidden for Codex too, so the gateway sentences apply there. -- A stdio MCP server is a `"": {"type": "stdio", "command": "...", "args": [...]}` entry in `--mcp-config`, next to the `http` entries. Claude starts the process itself in `/work`. Its startup timeout is `MCP_TIMEOUT`, which defaults to 30 seconds. A run with a stdio server sets `"env": {"MCP_TIMEOUT": "120000"}` in the `--settings` JSON, which takes effect and needs no podman `--env`: checked on Claude Code 2.1.330, a server that never answered was marked `failed` in the `init` line after about 6 seconds with `MCP_TIMEOUT=1500` in settings and after about 33 seconds without it. A run with no stdio server passes the same `--settings` as before. A server that cannot start shows as `"status":"failed"` in the `init` line, which the runner reports as an unavailable server. Claude does not expand `${NAME}` in a command or argument, but the factory refuses `${` anyway, see MCP server registry. +- A stdio MCP server is a `"": {"type": "stdio", "command": "...", "args": [...]}` entry in the MCP config JSON, next to the `http` entries. A run with a stdio server writes that JSON to `factory-mcp.json` in the config directory and passes its path to `--mcp-config`, see MCP stdio servers. Claude starts the process itself in `/work`. Its startup timeout is `MCP_TIMEOUT`, which defaults to 30 seconds. A run with a stdio server sets `"env": {"MCP_TIMEOUT": "120000"}` in the `--settings` JSON, which takes effect and needs no podman `--env`: checked on Claude Code 2.1.330, a server that never answered was marked `failed` in the `init` line after about 6 seconds with `MCP_TIMEOUT=1500` in settings and after about 33 seconds without it. A run with no stdio server passes the same `--settings` as before. A server that cannot start shows as `"status":"failed"` in the `init` line, which the runner reports as an unavailable server. Claude does not expand `${NAME}` in a command or argument, but the factory refuses `${` anyway, see MCP server registry. - Claude Code hooks run under whatever shell the container has, without the nix devShell. Write hook scripts for plain bash and test them that way. ## Running Codex in a worker @@ -197,7 +197,7 @@ The worker image carries Codex next to Claude Code, and the `AgentBackend` in `f - **Sessions.** Codex assigns the session id itself and reports it in `thread.started`, so the factory learns it from the stream and cannot pass it in advance the way it passes Claude's `--session-id`. The parser turns `thread.started` into an item the scheduler stores in the `sessions` table's agent-session-id column as soon as the line arrives, so a run that dies after that line can still resume. A resumed run uses `codex exec resume ` when the id is stored and a rollout file for it exists under `CODEX_HOME/sessions`, and otherwise starts a new session. Claude leaves the column empty, because it uses the factory's UUID. - **Structured output.** Each run ends with `--output-schema`, which makes the final agent message match the schema. OpenAI's strict rules want every property in `required` and `additionalProperties: false` on every object, so a stage that may leave a field out marks it nullable and the outcome resolution reads a `null` as absent. The text of the last `agent_message` item goes through the same outcome resolution as Claude's `structured_output`, so a missing output or an outcome the stage does not allow fails the run the same way. - **Config.** `CODEX_HOME=/codex` inside the worker, mounted from the job's `codex` directory on the host. The backend writes a `config.toml` there that sets `cli_auth_credentials_store = "file"` and no `project_doc_fallback_filenames`, so Codex keeps the login in the file rather than an OS keyring and reads a repository's `AGENTS.md` rather than its `CLAUDE.md`. -- **MCP.** Each active server becomes `-c mcp_servers..url="/mcp/"` and `-c mcp_servers..bearer_token_env_var="FACTORY_MCP_TOKEN"`, and the run token reaches the container through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the `podman` arguments and the log. A stdio server becomes `-c mcp_servers..command=""`, `-c mcp_servers..args=[...]` and `-c mcp_servers..startup_timeout_sec=120`, because Codex's default startup timeout is 10 seconds and a first `npx` or `uvx` start downloads the package. Values are TOML basic strings, with the backslash, quote and control characters escaped, so a quote, backslash or space in an argument arrives unchanged. The pinned 0.165.0 binary accepted these overrides, including an argument that held `"`, `\` and a space. A run with only stdio servers passes no `FACTORY_MCP_TOKEN`. A run with no active server passes no MCP flags and no token. The proxy, its run tokens, the tool toggles and the `mcp-tool-call` rows work for a Codex run unchanged, because they sit on the factory side. A run with an active server also gets the shared prompt paragraph that names the servers, asks the agent to load their tools first and covers gateway servers, the same paragraph a Claude run gets, see "Prompt boundary". +- **MCP.** Each active server becomes `-c mcp_servers..url="/mcp/"` and `-c mcp_servers..bearer_token_env_var="FACTORY_MCP_TOKEN"`, and the run token reaches the container through `--env FACTORY_MCP_TOKEN` with no value, so the token stays out of the `podman` arguments and the log. A stdio server becomes a `[mcp_servers.]` table in the `config.toml` the runner writes into `CODEX_HOME`, with `command`, `args` and `startup_timeout_sec = 120`, and no `-c` override, because Codex's default startup timeout is 10 seconds and a first `npx` or `uvx` start downloads the package. Values are TOML basic strings, with the backslash, quote and control characters escaped, so a quote, backslash or space in an argument arrives unchanged. The pinned 0.165.0 binary accepted the same keys as `-c` overrides, including an argument that held `"`, `\` and a space. A run with only stdio servers passes no `FACTORY_MCP_TOKEN`. A run with no active server passes no MCP flags and no token. The proxy, its run tokens, the tool toggles and the `mcp-tool-call` rows work for a Codex run unchanged, because they sit on the factory side. A run with an active server also gets the shared prompt paragraph that names the servers, asks the agent to load their tools first and covers gateway servers, the same paragraph a Claude run gets, see "Prompt boundary". - **Parser.** The Codex parser turns the JSON Lines into the same `AgentItem`s as Claude's stream parser. Agent messages, command executions with their exit code, file changes, MCP tool calls and errors become log lines in the same style, such as `tool mcp____` for an MCP call. It sums the `usage` of every `turn.completed` line for the cost estimate, see Job cost. A `turn.failed` carries its reason under `error.message` and a top-level `error` under `message`, and either without a final agent message fails the run with "the Codex run failed: ". A login Codex rejected mid-run surfaces as that failure, and the job page's Retry runs the task again once a new login is stored. A non-fatal item `error`, such as a startup warning, is a log line and does not fail the run. - The image installs one pinned Codex release, set by the `CODEX_VERSION` build arg (`0.165.0`). It downloads the `codex-package-x86_64-unknown-linux-musl` tarball from the `rust-v` GitHub release, unpacks it to `/opt/codex` and links `/opt/codex/bin/codex` as `/usr/local/bin/codex`. The build fails if `codex --version` does not report that version or `codex-code-mode-host` is missing. moon is x86_64, so the image pins that one asset rather than detect the architecture. @@ -287,7 +287,7 @@ Confirmed from the pinned CLI's own SDK types, `copilot-sdk/generated/session-ev - A tool call emits `tool.execution_start` then `tool.execution_complete`. The start event carries `data.toolName`, `data.arguments`, and, for an MCP tool, `data.mcpServerName` and `data.mcpToolName`; a shell tool (`bash`) carries `data.shellToolInfo.displayCommand`. The complete event carries `data.success` and, on failure, `data.error.message`, keyed to the start by `data.toolCallId` but with no tool name of its own. The parser logs the start as an `exec`, `edit` or `mcp____` line and notes a failed complete; see "Running Copilot in a worker". - `session.warning` carries `data.message`. The parser logs it. - `session.mcp_server_status_changed` carries `data.serverName`, `data.status` (`connected`, `failed`, `needs-auth`, `pending`, `disabled`, `stopped` or `not_configured`) and, for a failure, `data.error`. `session.mcp_servers_loaded` lists `data.servers` with the same `name`, `status` and `error`. Both are marked `ephemeral`. The parser turns a `failed` status in either into an unavailable-server warning, without the error text. These are the SDK's shapes, not a captured run, so the manual check confirms that the `-p --output-format json` stream carries them. -- A stdio server entry is `{"type":"local","command":"…","args":[…],"tools":["*"]}`. `type` is `"local" | "stdio"` in the SDK types, `timeout` is the tool-call timeout in milliseconds, and there is no startup timeout field. The binary accepts `--additional-mcp-config` with such an entry, but an unauthenticated run stops before it starts the server. +- A stdio server entry is `{"type":"local","command":"…","args":[…],"tools":["*"]}`. `type` is `"local" | "stdio"` in the SDK types, `timeout` is the tool-call timeout in milliseconds, and there is no startup timeout field. A run with a stdio server passes `--additional-mcp-config @`, which the help text documents for a file. The binary accepts `--additional-mcp-config` with such an entry, but an unauthenticated run stops before it starts the server. - These shapes are the SDK's, not a captured run. The manual check on moon (acceptance criterion 10) is the first authenticated tool-using run; if a shape differs there, the parser and this section are corrected then. ## Layout From ce6c5f7bcd65c09ca022fdc4fb9575b5297a0432 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:36:47 +0000 Subject: [PATCH 3/3] crates: replace the stdio MCP config files atomically Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-runner/src/agent.rs | 11 +++++++++++ crates/factory-runner/src/claude.rs | 4 ++-- crates/factory-runner/src/codex.rs | 6 ++++-- crates/factory-runner/src/copilot.rs | 5 ++--- crates/factory-runner/tests/codex.rs | 23 +++++++++++++++++++++++ crates/factory-runner/tests/copilot.rs | 23 +++++++++++++++++++++++ crates/factory-runner/tests/runner.rs | 23 +++++++++++++++++++++++ docs/design.md | 2 +- 8 files changed, 89 insertions(+), 8 deletions(-) diff --git a/crates/factory-runner/src/agent.rs b/crates/factory-runner/src/agent.rs index 4a521458..759277f2 100644 --- a/crates/factory-runner/src/agent.rs +++ b/crates/factory-runner/src/agent.rs @@ -200,3 +200,14 @@ pub fn backend(agent: Agent) -> Option<&'static dyn AgentBackend> { Agent::Copilot => Some(&CopilotAgent), } } + +/// Writes `contents` to `dir/name` through a fresh temporary file in `dir` and a +/// rename. A previous worker can leave a symlink at `name`, and a rename replaces +/// the link itself, where an in-place write would follow it out of `dir`. +pub(crate) fn write_replacing(dir: &Path, name: &str, contents: &str) -> std::io::Result<()> { + use std::io::Write as _; + let mut file = tempfile::NamedTempFile::new_in(dir)?; + file.write_all(contents.as_bytes())?; + file.persist(dir.join(name)).map_err(|err| err.error)?; + Ok(()) +} diff --git a/crates/factory-runner/src/claude.rs b/crates/factory-runner/src/claude.rs index 5eed6960..ebb26b74 100644 --- a/crates/factory-runner/src/claude.rs +++ b/crates/factory-runner/src/claude.rs @@ -12,7 +12,7 @@ use std::path::Path; use factory_core::Agent; -use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult}; +use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, write_replacing}; use crate::outcome::{Expect, event_from_result}; use crate::stream::{StreamItem, parse_line}; use crate::worker::{ @@ -70,7 +70,7 @@ impl AgentBackend for ClaudeAgent { fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> { match run.mcp.as_ref().filter(|mcp| mcp.has_stdio()) { - Some(mcp) => fs::write(run.config_dir.join(MCP_CONFIG_FILE), mcp_config(mcp)), + Some(mcp) => write_replacing(&run.config_dir, MCP_CONFIG_FILE, &mcp_config(mcp)), None => Ok(()), } } diff --git a/crates/factory-runner/src/codex.rs b/crates/factory-runner/src/codex.rs index 89cd8c0c..7006b09f 100644 --- a/crates/factory-runner/src/codex.rs +++ b/crates/factory-runner/src/codex.rs @@ -21,7 +21,9 @@ use std::fmt::Write as _; use factory_core::Agent; use serde_json::Value; -use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, TokenUsage}; +use crate::agent::{ + AgentBackend, AgentItem, Credential, PromptStyle, RunResult, TokenUsage, write_replacing, +}; use crate::outcome::{Expect, event_from_output, failed_event}; use crate::stream::LogLine; use crate::worker::{ @@ -122,7 +124,7 @@ impl AgentBackend for CodexAgent { ); } } - fs::write(run.config_dir.join(CONFIG_FILE), config)?; + write_replacing(&run.config_dir, CONFIG_FILE, &config)?; fs::write( run.config_dir.join(SCHEMA_FILE), run.expect.strict_schema().to_string(), diff --git a/crates/factory-runner/src/copilot.rs b/crates/factory-runner/src/copilot.rs index 42e80f8a..6b9d05ae 100644 --- a/crates/factory-runner/src/copilot.rs +++ b/crates/factory-runner/src/copilot.rs @@ -16,13 +16,12 @@ //! the stream, so the parser keys a failure off a non-zero `result.exitCode`. use std::ffi::OsString; -use std::fs; use std::path::Path; use factory_core::Agent; use serde_json::Value; -use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult}; +use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, write_replacing}; use crate::outcome::{Expect, event_from_output, failed_event}; use crate::stream::LogLine; use crate::worker::{ @@ -100,7 +99,7 @@ impl AgentBackend for CopilotAgent { fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> { match run.mcp.as_ref().filter(|mcp| mcp.has_stdio()) { - Some(mcp) => fs::write(run.config_dir.join(MCP_CONFIG_FILE), mcp_config(mcp)), + Some(mcp) => write_replacing(&run.config_dir, MCP_CONFIG_FILE, &mcp_config(mcp)), None => Ok(()), } } diff --git a/crates/factory-runner/tests/codex.rs b/crates/factory-runner/tests/codex.rs index 797f66b7..d5218b9e 100644 --- a/crates/factory-runner/tests/codex.rs +++ b/crates/factory-runner/tests/codex.rs @@ -711,3 +711,26 @@ async fn a_run_reports_the_thread_id_usage_and_reads_the_refreshed_login_back() .unwrap(); assert_eq!(schema, Expect::Spec.strict_schema()); } + +#[test] +fn a_symlink_in_the_codex_config_dir_is_replaced_not_followed() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("codex")).unwrap(); + let target = dir.path().join("outside"); + fs::write(&target, "untouched").unwrap(); + std::os::unix::fs::symlink(&target, dir.path().join("codex/config.toml")).unwrap(); + let mut run = codex_run(dir.path(), SessionRun::Start(THREAD.into())); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + backend(Agent::Codex).unwrap().prepare(&run).unwrap(); + assert_eq!(fs::read_to_string(&target).unwrap(), "untouched"); + let written = dir.path().join("codex/config.toml"); + assert!(!fs::symlink_metadata(&written).unwrap().is_symlink()); + assert!( + fs::read_to_string(&written) + .unwrap() + .contains("playwright-mcp") + ); +} diff --git a/crates/factory-runner/tests/copilot.rs b/crates/factory-runner/tests/copilot.rs index 2551a40a..933e4b59 100644 --- a/crates/factory-runner/tests/copilot.rs +++ b/crates/factory-runner/tests/copilot.rs @@ -881,3 +881,26 @@ async fn a_checkpoint_is_logged_when_the_run_dies_before_its_result_line() { "{log:?}" ); } + +#[test] +fn a_symlink_in_the_copilot_config_dir_is_replaced_not_followed() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("copilot")).unwrap(); + let target = dir.path().join("outside"); + fs::write(&target, "untouched").unwrap(); + std::os::unix::fs::symlink(&target, dir.path().join("copilot/factory-mcp.json")).unwrap(); + let mut run = copilot_run(dir.path(), SessionRun::Start(SESSION.into())); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + backend(Agent::Copilot).unwrap().prepare(&run).unwrap(); + assert_eq!(fs::read_to_string(&target).unwrap(), "untouched"); + let written = dir.path().join("copilot/factory-mcp.json"); + assert!(!fs::symlink_metadata(&written).unwrap().is_symlink()); + assert!( + fs::read_to_string(&written) + .unwrap() + .contains("playwright-mcp") + ); +} diff --git a/crates/factory-runner/tests/runner.rs b/crates/factory-runner/tests/runner.rs index ccd88a97..a9bfb0ca 100644 --- a/crates/factory-runner/tests/runner.rs +++ b/crates/factory-runner/tests/runner.rs @@ -2063,3 +2063,26 @@ fn the_gap_prompt_carries_the_input_and_the_rules_of_its_type() { assert!(text.contains("Build-Depends") && text.contains("debian/patches")); assert!(text.contains("unavailable")); } + +#[test] +fn a_symlink_in_the_claude_config_dir_is_replaced_not_followed() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("claude")).unwrap(); + let target = dir.path().join("outside"); + fs::write(&target, "untouched").unwrap(); + std::os::unix::fs::symlink(&target, dir.path().join("claude/factory-mcp.json")).unwrap(); + let mut run = worker_run(dir.path(), SessionRun::Start(SESSION.into())); + run.mcp = Some(McpConfig { + proxy: None, + servers: vec![stdio_entry()], + }); + backend(Agent::Claude).unwrap().prepare(&run).unwrap(); + assert_eq!(fs::read_to_string(&target).unwrap(), "untouched"); + let written = dir.path().join("claude/factory-mcp.json"); + assert!(!fs::symlink_metadata(&written).unwrap().is_symlink()); + assert!( + fs::read_to_string(&written) + .unwrap() + .contains("playwright-mcp") + ); +} diff --git a/docs/design.md b/docs/design.md index 2d46eed0..f5275f40 100644 --- a/docs/design.md +++ b/docs/design.md @@ -36,7 +36,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | MCP proxy | The factory runs an HTTP proxy for MCP traffic on its own listener, `FACTORY_PROXY_LISTEN`, which the Quadlet unit sets to `0.0.0.0:8081`, separate from the dashboard on `127.0.0.1:8080`. The factory container and its workers share the `factory` podman network, which `install.sh` creates, so a worker reaches the proxy by the factory's container name at `FACTORY_PROXY_URL` (`http://factory:8081`), while the dashboard port, published only to the host loopback, stays out of a worker's reach. For each agent run with at least one active remote server the scheduler issues a run token through `RunTokens`: 256 random bits held only in the factory's memory, scoped to the job and the remote servers active for the run's stage. The scheduler revokes the token when the worker exits, whether the run succeeded, failed or was cancelled, and a factory restart drops every token. The worker gets `claude --mcp-config` with one `http` entry per active remote server, each pointing at `http://factory:8081/mcp/` and carrying `Authorization: Bearer ` as its only header. A run with no active server gets no MCP flags, so its arguments are unchanged, and a run with only stdio servers gets no token, and check runs and every non-agent container get no config and no token. The proxy answers 401 to a missing, unknown or revoked token and 403 to a server outside the token's scope. For an authorized request it drops the worker's `Authorization` header, adds the project's stored headers, and forwards the method, path suffix, query, body and the protocol headers, `Content-Type`, `Accept`, `Mcp-Session-Id`, `MCP-Protocol-Version` and `Last-Event-ID`, to the server's URL. It streams a `text/event-stream` response without buffering it, except the event that answers a filtered `tools/list`, see MCP tool toggles, and supports the POST, GET and DELETE that streamable HTTP uses. It follows no redirect, so a 3xx cannot carry the headers to another host and is returned to the worker as it is. It uses a 10-second connect timeout and no total timeout, so a streaming response may stay open for the length of the run. The credential stays out of the worker because the worker runs with `bypassPermissions`: it could otherwise read the value from its config, arguments or environment, and a prompt injection in a repository or an MCP response could make it print or send the key. The proxy keeps the value on the factory side, so the worker holds only a run token the proxy swaps for the real headers. The proxy also reports each `tools/call` it forwards, which the factory records as an `mcp-tool-call` row, see Job MCP tool calls. The proxy's client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, the same list the connection check uses. Unset, it trusts the built-in roots alone. A stdio server bypasses the proxy: it gets no run token and no entry that points at the proxy, and `StoreUpstreams::resolve` returns `None` for it, see MCP stdio servers. | | MCP unavailable servers | An enabled server that is unreachable when a run starts does not fail the run. The run goes on without the server's tools, as Claude Code does. Two paths report it. The runner reads the `mcp_servers` list in the stream-json `system`/`init` line and warns about each active server whose status is not `connected`. The proxy warns when it cannot reach the server, a connection times out, or the server answers 5xx. The scheduler also warns about a server it skipped because a stored header value would not decrypt, so a broken credential never lands in a worker's config. All three funnel through `McpWarnings`, which dedupes per run so a server is warned at most once, and writes the warning through `Store::record_mcp_unavailable`: a factory line to the job log that names the server and the reason, and an `mcp-unavailable` row in `job_events` with `: ` in its `detail`, written the way `add_cost` writes a cost row, so it changes neither the job's stage nor its turn. The reason names no credential. The job page timeline shows the row as a note under the step the run was in. A stdio server that fails to start is reported the same way and does not fail the run. Claude reports it in the same `init` line, with a status of `failed`. Copilot's SDK types define `session.mcp_server_status_changed` and `session.mcp_servers_loaded` events whose server status can be `failed`, and the parser maps a failed server in either to the warning, ahead of its ephemeral-event skip, because both are marked ephemeral. The reason is the status only, because the CLI's error text can quote the command's output. No authenticated Copilot run has shown that the CLI writes these events to `--output-format json`, so the manual check on moon confirms it. Codex 0.165.0 writes nothing to `exec --json` or stderr for a stdio server whose command does not exist, so a Codex run gets no warning for a stdio server that fails to start, and the agent finds out when its tools are missing. | | MCP connection check | A project's page for a server has a "Refresh connection" button that tests the server with that project's saved header values and refreshes the project's list of its tools, see MCP tool toggles. It posts to `POST /settings/projects//mcp//check` through htmx, which swaps the returned HTML fragment into a result area, so the page does not reload and unsaved input survives. The handler resolves the saved URL and the project's saved values through `StoreUpstreams`, the same resolver the proxy uses, so the check and a real run send the same headers. It ignores any form field posted with the request, so an unsaved value typed into the page is never sent, and the hint says to save first to check new ones. An unknown project or server gives 404. The check sends one JSON-RPC `initialize` POST, whose `clientInfo` carries the name `factory` and the crate version because the MCP schema requires both and a strict server such as Composio's rejects a request without `version`, with `Content-Type: application/json` and `Accept: application/json, text/event-stream` plus the project's values, follows no redirect like the proxy, uses the proxy's 10-second connect timeout, a 15-second total timeout, and reads at most 1 MiB of the body. Success is a 2xx reply, JSON or SSE, whose `result` carries a `protocolVersion`. The result names the server and version when the reply gives them. A 2xx reply with a JSON-RPC `error` shows the error's code and message, cut to 300 characters, with every header value the check sent replaced by `[redacted]`, since a server may echo the request. On success it sends a best-effort `DELETE` with any `Mcp-Session-Id` to end the session. The result messages cover a reachable MCP server, an unreachable host, a timeout, a 401 or 403 that points to the project's header values, another 3xx, 4xx or 5xx with a 3xx `Location`, a 2xx JSON-RPC error, and a 2xx that is not an MCP reply. A declared header with no stored value is named in the result, and the check runs without it. No header value reaches the fragment, a log line or an error. The result is not stored: reloading the page clears it. The HTTP part sits behind the `McpChecker` trait, held by the dashboard the way it holds `RepoChecker`, so a test uses a fake and the real `HttpMcpChecker` is tested against a local `http://` server. The "Add server" button runs no check, because the header values belong to projects and the add form has none; the per-project check is the one the requester chose. The client trusts the root certificates in the PEM file `FACTORY_MCP_CA_FILE` next to the built-in roots, and the proxy's client trusts the same list. reqwest uses its own bundled roots, so `SSL_CERT_FILE` has no effect, and a server with a self-signed or internal CA certificate could not pass the check. The browser tests' stub MCP server needs this, and so does an operator's internal server. A file that is unreadable or holds no certificate stops the factory at startup, so a typo does not leave a server silently untrusted. Unset, the trusted roots are unchanged. A stdio server runs inside the worker, so the check cannot reach it. `check_mcp_server` answers a stdio server with a 400 and runs nothing. A stdio server has no connection check. It runs inside the worker, so the factory has nothing to reach, and the route answers a stdio server with a 400 and runs nothing. A check would need a throwaway container that starts the command and lists its tools, which is a follow-up. | -| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. When a stdio server is active for a run's project and stage, the scheduler passes its name, command and arguments to the runner in `McpConfig`, and each backend writes the entry its CLI reads. The arguments are the registry's base arguments followed by the project's extra arguments, read on every run. The proxy part of `McpConfig`, the URL and the run token, is set only when a remote server is active, so a run with only stdio servers issues no run token and passes no `FACTORY_MCP_TOKEN`. A stdio run adds no `--volume`, `--env` or `--network` flag to `podman run`. The entries go into a file in the job's agent config directory, which the run already mounts, and not into the command line, because Linux rejects one argument of 128 KiB or more and 64 base and extra arguments of 4096 bytes can exceed that. Claude reads `--mcp-config /claude/factory-mcp.json`, Copilot reads `--additional-mcp-config @/copilot/factory-mcp.json`, and Codex reads the stdio tables in its `config.toml`. The runner writes the file in `AgentBackend::prepare`, before the container starts. The entry shapes, the startup timeouts and the `${` rule are in each agent's section: "Running Claude Code in a worker", "Running Codex in a worker" and "Copilot CLI facts". A stdio server that fails to start does not fail the run, see MCP unavailable servers, and its tool calls are read from the agent's output, see Job MCP tool calls. | +| MCP stdio servers | A stdio server is a command the agent starts inside the worker container, as a child process of the agent that talks to it over stdin and stdout. It bypasses the proxy, and that has a cost. The factory stores no secret for it, so an admin must not put one in an argument, because the agent runs with `bypassPermissions` and can read every argument. The factory cannot enforce a tool toggle, because it never sees the traffic, so a toggle could only hide a tool from the model. It has no connection check or tool list, because both need a throwaway container. The runner reads its tool calls from the agent's output instead of recording them in the proxy. A stdio server is admin-only for the same reason as the rest of the registry, see Factory admins. When a stdio server is active for a run's project and stage, the scheduler passes its name, command and arguments to the runner in `McpConfig`, and each backend writes the entry its CLI reads. The arguments are the registry's base arguments followed by the project's extra arguments, read on every run. The proxy part of `McpConfig`, the URL and the run token, is set only when a remote server is active, so a run with only stdio servers issues no run token and passes no `FACTORY_MCP_TOKEN`. A stdio run adds no `--volume`, `--env` or `--network` flag to `podman run`. The entries go into a file in the job's agent config directory, which the run already mounts, and not into the command line, because Linux rejects one argument of 128 KiB or more and 64 base and extra arguments of 4096 bytes can exceed that. Claude reads `--mcp-config /claude/factory-mcp.json`, Copilot reads `--additional-mcp-config @/copilot/factory-mcp.json`, and Codex reads the stdio tables in its `config.toml`. The runner writes the file in `AgentBackend::prepare`, before the container starts, through a temporary file in the same directory and a rename, because a previous worker can leave a symlink at the name and an in-place write would follow it out of the job directory. The entry shapes, the startup timeouts and the `${` rule are in each agent's section: "Running Claude Code in a worker", "Running Codex in a worker" and "Copilot CLI facts". A stdio server that fails to start does not fail the run, see MCP unavailable servers, and its tool calls are read from the agent's output, see Job MCP tool calls. | | MCP stdio isolation | A stdio server is shared as a registry entry and nothing else. It is a child process of the agent, in the container of one run of one job, and that container is started with `--rm`, so the server dies with it. No server process is shared between runs, jobs or projects, and none outlives a run. It sees what the agent sees: the job's checkout at `/work`, the job's own agent config directory, the read-only agents directory and the `/nix` volume. What it writes elsewhere, such as the `npx` cache in `~/.npm`, a `uvx` cache or a browser profile, lives in the container's own filesystem and is deleted with the container. The factory adds no shared cache volume and no mount for it. It uses no run token and no stored secret, so it has no credential that could leak to another project. A project runs a server only after one of its own collaborators enables it, and the project's extra arguments, the `mcp-tool-call` rows and the warnings are stored per project or per job. Only an admin changes the command and base arguments, and the server's page lists the projects that use it, so the admin sees who an edit reaches. One resource is shared: the `/nix` volume that every worker of every project mounts read-write through `FACTORY_WORKER_VOLUMES`. Store paths are content-addressed and agents already fill it with `nix shell nixpkgs#...`. Any other volume an operator adds to `FACTORY_WORKER_VOLUMES` is shared the same way. The factory does not harden or split that volume per project. | | MCP tool toggles | A project can turn off single tools of an MCP server it uses. Every tool is on by default, so the factory stores the tools that are off, and a project with none off behaves as before. The setting is per project and server and applies to all five stages, without a per-stage grid. A tool a server adds later starts on. The settings page marks it "new" so an operator sees it. The `project_mcp_tools` table holds the last tool list per project and server, keyed by project, server and tool name, with the tool's description, an `offered` flag, a `disabled` flag and the number of the refresh that first saw it. `project_mcp_tool_refreshes` counts each project and server's refreshes, so a tool is "new" when the latest refresh first saw it and is not the first one. The list is per project because a server may offer different tools for different credentials. "Refresh connection" fills the table, see MCP connection check: after a successful `initialize` it sends `notifications/initialized` and pages through `tools/list` by its cursor with the negotiated `MCP-Protocol-Version` and the `Mcp-Session-Id`. The same 15-second total timeout covers the whole exchange, and each reply is read up to 1 MiB. Only a complete list replaces the stored one. A tool missing from it keeps its row with `offered` cleared, so a turned-off tool stays off if the server offers it again, and the page lists it as "no longer offered". A failed list keeps the old rows and the result says the tools could not be listed. The refresh route returns the page's refresh area, the button, the result and the tool list, and htmx replaces that area, found from the button with `closest .mcp-refresh`. The swap drops unsaved changes to that list's checkboxes, and the hint says so. The list sits on the project's page for the server as one checkbox per stored tool, checked when on, with its description. Each shown tool posts a hidden `mcp..shown.` field and, when checked, `mcp..tool.`. A server name has no `.`, so the handler splits the tool name off after the prefix. The save handler turns off the shown tools left unchecked and turns on the checked ones. It leaves a tool the form did not show as it is, so a refresh between render and save turns nothing off by accident. The proxy enforces the setting, because a worker with `bypassPermissions` and a run token could call a tool with `curl` that a Claude Code flag only hid from the model. `StoreUpstreams` returns the server's turned-off tool names with its headers, read on each request, so a change reaches a run in flight at its next request. For a POST, the proxy parses the body it already buffers as JSON-RPC, rejecting duplicate keys so it and the server cannot read two different tool names. A `tools/call` whose `params.name` is off gets a JSON-RPC error that names the tool as turned off for the project, with the request's `id`, and the proxy forwards nothing. A batch array holding such a call gets a 403 and nothing is forwarded. When the server has a tool turned off, a POST body that does not parse gets a 400 rather than being forwarded. A `tools/list` reply is buffered up to 4 MiB and the turned-off tools are removed from `result.tools`, in a JSON body or in the SSE event carrying the response, with other SSE events passed through as they are. A reply over the cap or one that does not parse is relayed unchanged, and the call block still applies. A stream resumed by `Last-Event-ID` may replay an unfiltered list, and the call block applies there too. Every other request and response streams as before. Each blocked call goes through `McpWarnings`, deduped per run, server and tool, and `Store` writes a factory line to the job log and an `mcp-tool-blocked` row in `job_events` with `: ` in its `detail`, which the job page timeline shows as a note under the step. Deleting a server deletes its tool rows with its `project_mcp` rows. A rename loses them like the stored values. An edit that changes the URL's origin clears `offered` on every row and keeps each `disabled` flag until the next refresh. A stdio server has no tool toggles. The proxy is what enforces them, a stdio server bypasses it, and listing its tools needs the same throwaway container as the connection check. A toggle could then only hide a tool from the model, not block it. Both are a follow-up. | | Job MCP tool calls | The proxy records every call a job makes to a remote server, and the scheduler records every call to a stdio server from the agent's output. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. |