From 20c5f59692946b0b043c7f859a2a4deb109d2bdb Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:56:20 +0000 Subject: [PATCH 1/2] factory-server: mcp: let a project append stdio arguments A project's page for a stdio server has the enabled switch, the stages, the server's command and base arguments read-only, and an Extra arguments list stored per project and server. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/pages.rs | 185 ++++++++++++++------ crates/factory-server/src/store.rs | 51 +++++- crates/factory-server/src/web.rs | 37 +++- crates/factory-server/tests/dashboard.rs | 206 ++++++++++++++++++++++- crates/factory-server/tests/mcp.rs | 113 +++++++++++++ docs/design.md | 8 +- e2e/tests/project-settings.spec.ts | 58 +++++++ 7 files changed, 593 insertions(+), 65 deletions(-) diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index fb92187..bbebb7f 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -849,6 +849,17 @@ pub struct ServerSettings { pub headers: Vec, /// The tools the last refresh stored, each with its on or off state. pub tools: Vec, + /// The command line parts when the server is stdio, `None` when it is remote. + pub stdio: Option, +} + +/// A stdio server as a project's page shows it. +pub struct StdioSettings { + pub command: String, + /// The registry's base arguments. + pub args: Vec, + /// The arguments this project appends after the base ones. + pub extra_args: Vec, } /// One declared header in a project's server block. `set` is whether a value is @@ -2237,6 +2248,9 @@ fn project_servers_card(project: &ProjectSettings, admin: bool) -> Markup { span.server-name { (server.name) } span.hint.server-url { (usage_line(server.enabled, server.stages)) + @if server.stdio.is_some() { + " · stdio" + } @if !server.tools.is_empty() { " · " (on) " of " (server.tools.len()) " tools on" } @@ -2273,24 +2287,91 @@ pub fn settings_project_mcp( h1 { (server.name) " for " (project.shown) } p.meta { @if nav.admin { - "The server's URL and header names are on " + @if server.stdio.is_some() { + "The server's command and base arguments are on " + } @else { + "The server's URL and header names are on " + } a href={ "/settings/mcp/" (crate::web::query_escape(&server.name)) } { "its own page" } ". " } "The values here are this project's alone." } - @if !secrets_available { + @if !secrets_available && server.stdio.is_none() { p.hint.bad { "The master key is missing, so header values cannot be saved. The enabled switch, stages and tools still save." } } form.card.settings-form method="post" action=(project_mcp_href(&project.id, &server.name)) { (project_server_block(project, server, secrets_available)) (save_bar("Save")) } - script { (PreEscaped(MCP_TOOLS)) } + @if server.stdio.is_some() { + script { (PreEscaped(MCP_ROWS)) } + } @else { + script { (PreEscaped(MCP_TOOLS)) } + } }, ) } +/// The part of a stdio server's project block below the stage checkboxes: the +/// command and base arguments read-only, the project's extra arguments, and the +/// command line a run starts. +fn stdio_block(stdio: &StdioSettings) -> Markup { + let line = std::iter::once(&stdio.command) + .chain(&stdio.args) + .chain(&stdio.extra_args) + .map(|part| shell_quote(part)) + .collect::>() + .join(" "); + html! { + div.field { + span.label { "Command" } + p { code { (stdio.command) } } + @if !stdio.args.is_empty() { + span.label { "Base arguments" } + p { @for arg in &stdio.args { code.mcp-arg { (arg) } " " } } + } + p.hint { "Set by an admin on the server's own page. They run inside the worker of every project that turns the server on." } + } + div.field { + span.label { "Extra arguments" } + div.mcp-args { + @for arg in &stdio.extra_args { + @if arg.contains(['\r', '\n']) { + (escaped_arg_row(arg)) + } @else { + (arg_row(arg)) + } + } + @for _ in 0..3 { + (arg_row("")) + } + } + template { (arg_row("")) } + button.add-arg type="button" { "Add argument" } + p.hint { "Appended after the server's own arguments, in this order, for this project's runs only. The agent can read them, so no secret belongs here. An argument is passed as one value, with no shell splitting, and may not contain ${. A change applies at the job's next run." } + } + div.field { + span.label { "Command line a run starts" } + p { code.mcp-command-line { (line) } } + } + p.hint { "This server runs inside the worker, so the factory cannot check its connection or turn off single tools." } + } +} + +/// `part` as a shell word, so the preview shows where one argument ends. +fn shell_quote(part: &str) -> String { + let plain = !part.is_empty() + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_=./:@%+,".contains(&b)); + if plain { + part.to_owned() + } else { + format!("'{}'", part.replace('\'', "'\\''")) + } +} + /// The header-name rows a server form shares: one text box per stored name, each /// with a Remove button, then one empty box for a new name, then an "Add header" /// button and the given `hint`. The names post as a repeated `header` field. The @@ -2940,7 +3021,11 @@ fn stage_panel(project: &ProjectSettings, stage: &str, selected: bool, admin: bo @if server.headers.iter().any(|header| !header.set) { span.bad { "Key missing. " } } - a href=(project_mcp_href(name, &server.name)) { "Key and tools for " (server.name) } + @if server.stdio.is_some() { + a href=(project_mcp_href(name, &server.name)) { "Arguments for " (server.name) } + } @else { + a href=(project_mcp_href(name, &server.name)) { "Key and tools for " (server.name) } + } } } } @@ -2985,50 +3070,54 @@ fn project_server_block( let base = format!("mcp.{}", server.name); let stages = server.stages; html! { - div.mcp-project { - div.field { - label.check { - input type="checkbox" name={ (base) ".enabled" } value="on" - checked[server.enabled]; - " Run this server for " (project.shown) - } - } - div.field { - p.hint { "The stages it runs in. An enabled server needs at least one." } - @for (stage, on) in [ - ("clarify", stages.clarify), - ("spec", stages.spec), - ("plan", stages.plan), - ("implement", stages.implement), - ("review", stages.review), - ] { - label.check { - input type="checkbox" name={ (base) ".stage." (stage) } value="on" - checked[on]; - " " (stage) - } - } - } - @for header in &server.headers { - div.field { - label for={ (base) "-header-" (header.name) } { (header.name) } - input id={ (base) "-header-" (header.name) }.wide type="password" - name={ (base) ".header." (header.name) } - autocomplete="off" placeholder=(if header.set { "set" } else { "not set" }) - disabled[!secrets_available]; - label.check { - input type="checkbox" name={ (base) ".clear." (header.name) } value="on"; - " Clear the stored value" - } - p.hint { - @if header.set { "A value is stored. " } @else { "No value is stored. " } - "Type a new value to replace it. An empty field keeps it." - } - } - } - (mcp_refresh(&project.id, &server.name, &server.tools, None)) - } - } + div.mcp-project { + div.field { + label.check { + input type="checkbox" name={ (base) ".enabled" } value="on" + checked[server.enabled]; + " Run this server for " (project.shown) + } + } + div.field { + p.hint { "The stages it runs in. An enabled server needs at least one." } + @for (stage, on) in [ + ("clarify", stages.clarify), + ("spec", stages.spec), + ("plan", stages.plan), + ("implement", stages.implement), + ("review", stages.review), + ] { + label.check { + input type="checkbox" name={ (base) ".stage." (stage) } value="on" + checked[on]; + " " (stage) + } + } + } + @if let Some(stdio) = &server.stdio { + (stdio_block(stdio)) + } @else { + @for header in &server.headers { + div.field { + label for={ (base) "-header-" (header.name) } { (header.name) } + input id={ (base) "-header-" (header.name) }.wide type="password" + name={ (base) ".header." (header.name) } + autocomplete="off" placeholder=(if header.set { "set" } else { "not set" }) + disabled[!secrets_available]; + label.check { + input type="checkbox" name={ (base) ".clear." (header.name) } value="on"; + " Clear the stored value" + } + p.hint { + @if header.set { "A value is stored. " } @else { "No value is stored. " } + "Type a new value to replace it. An empty field keeps it." + } + } + } + (mcp_refresh(&project.id, &server.name, &server.tools, None)) + } + } + } } /// The "Refresh connection" button, its result area and the server's tool list diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index 1198670..bd14d39 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -208,6 +208,12 @@ CREATE TABLE IF NOT EXISTS project_mcp_tool_refreshes ( latest INTEGER NOT NULL, PRIMARY KEY (project, server) ); +CREATE TABLE IF NOT EXISTS project_mcp_args ( + project TEXT NOT NULL, + server TEXT NOT NULL, + args TEXT NOT NULL, + PRIMARY KEY (project, server) +); CREATE TABLE IF NOT EXISTS cost_closed_jobs ( job_id INTEGER PRIMARY KEY REFERENCES jobs (id) ); @@ -3213,7 +3219,7 @@ impl Store { /// The deleted configuration is the project's rows in `projects`, /// `project_models`, `project_settings`, `project_gates`, `project_efforts`, /// `project_agents`, `project_mcp`, `project_mcp_tools`, - /// `project_mcp_tool_refreshes`, `project_totals` and + /// `project_mcp_tool_refreshes`, `project_mcp_args`, `project_totals` and /// `project_collaborators`, `project_maintenance`, `renovate_prs`, its MCP header values in `secrets`, its /// `job_costs` rows, and the `cost` rows in `job_events` for its jobs. With /// no collaborator rows left, the project and its surviving jobs are visible @@ -3260,6 +3266,7 @@ impl Store { "project_mcp", "project_mcp_tools", "project_mcp_tool_refreshes", + "project_mcp_args", "project_totals", "project_collaborators", "project_maintenance", @@ -4366,6 +4373,7 @@ impl Store { tx.execute("DELETE FROM secrets WHERE server = ?1", [name])?; tx.execute("DELETE FROM project_mcp WHERE server = ?1", [name])?; tx.execute("DELETE FROM project_mcp_tools WHERE server = ?1", [name])?; + tx.execute("DELETE FROM project_mcp_args WHERE server = ?1", [name])?; tx.execute( "DELETE FROM project_mcp_tool_refreshes WHERE server = ?1", [name], @@ -4449,6 +4457,47 @@ impl Store { Ok(()) } + /// The extra arguments `project` appends after the base arguments of the + /// stdio server `server`, in order. Empty when none are stored. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn project_mcp_args(&self, project: &str, server: &str) -> Result, StoreError> { + let stored: Option = self + .conn() + .query_row( + "SELECT args FROM project_mcp_args WHERE project = ?1 AND server = ?2", + params![project, server], + |row| row.get(0), + ) + .optional()?; + Ok(stored + .and_then(|json| serde_json::from_str(&json).ok()) + .unwrap_or_default()) + } + + /// Saves `project`'s extra arguments for `server`, writing only this row. + /// The caller has validated them with [`crate::mcp::validate_args`]. + /// + /// # Errors + /// + /// Fails on a database error. + pub fn save_project_mcp_args( + &self, + project: &str, + server: &str, + args: &[String], + ) -> Result<(), StoreError> { + let json = serde_json::to_string(args)?; + self.conn().execute( + "INSERT INTO project_mcp_args (project, server, args) VALUES (?1, ?2, ?3) + ON CONFLICT (project, server) DO UPDATE SET args = excluded.args", + params![project, server, json], + )?; + Ok(()) + } + /// The tools stored for `project`'s use of `server`, sorted by name. Empty /// until a refresh has listed the server's tools. /// diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 976bece..54fc9fa 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -2028,8 +2028,6 @@ fn project_settings( .store .mcp_servers()? .into_iter() - // Runs do not carry a stdio server yet, so a project has no switch for it. - .filter(|server| server.as_remote().is_some()) .map(|server| server_settings(state, name, server)) .collect::, StoreError>>()?; let agents = state @@ -2255,9 +2253,6 @@ fn save_posted_gates(store: &Store, project: &str, form: &ProjectForm) -> Result /// own page. A server that is off and stays off is not written. fn save_pipeline_mcp(state: &AppState, project: &str, form: &ProjectForm) -> Result<(), AppError> { for server in state.store.mcp_servers()? { - if server.as_remote().is_none() { - continue; - } let base = format!("mcp.{}", server.name); if !form.ticked(&format!("{base}.pipeline")) { continue; @@ -3303,6 +3298,14 @@ fn server_settings( server: McpServer, ) -> Result { let saved = state.store.project_mcp(project, &server.name)?; + let stdio = match server.as_stdio() { + Some((command, args)) => Some(pages::StdioSettings { + command: command.to_owned(), + args: args.to_vec(), + extra_args: state.store.project_mcp_args(project, &server.name)?, + }), + None => None, + }; let declared = server.as_remote().map_or(&[][..], |(_, headers)| headers); let headers = declared .iter() @@ -3324,6 +3327,7 @@ fn server_settings( enabled: saved.enabled, stages: saved.stages, headers, + stdio, }) } @@ -3339,7 +3343,6 @@ fn project_and_server( state .store .mcp_server(server)? - .filter(|server| server.as_remote().is_some()) .ok_or_else(|| AppError::NotFound(format!("no MCP server named {server:?}"))) } @@ -3370,7 +3373,7 @@ async fn show_project_mcp( } /// Saves a project's settings for one server: whether it runs, its stages, its -/// header values and its tools. Everything is checked before any write, so a +/// header values and its tools, or for a stdio server its extra arguments. Everything is checked before any write, so a /// rejected submit changes nothing. An enabled server needs a stage, and a /// header value cannot be set while the secret store is unavailable. async fn save_project_mcp( @@ -3380,6 +3383,16 @@ async fn save_project_mcp( Form(pairs): Form>, ) -> Result { let registered = project_and_server(&state, &headers, &project, &server)?; + // The extra arguments are a repeated field, which the map below would + // collapse, so they are read from the pairs in order. + let mut extra_args = Vec::new(); + for (key, value) in &pairs { + match key.as_str() { + "arg" => extra_args.push(value.clone()), + "arg_escaped" => extra_args.push(unescape_arg(value)?), + _ => {} + } + } let form = ProjectForm(pairs.into_iter().collect()); let base = format!("mcp.{}", registered.name); let settings = McpProjectSettings { @@ -3395,6 +3408,11 @@ async fn save_project_mcp( if settings.enabled && !settings.stages.any() { return Err(McpError::NoStage(registered.name).into()); } + let extra_args = if registered.as_stdio().is_some() { + Some(crate::mcp::validate_args(&extra_args)?) + } else { + None + }; let value = |header: &str| { form.get(&format!("{base}.header.{header}")) .filter(|value| !value.is_empty()) @@ -3430,6 +3448,11 @@ async fn save_project_mcp( state .store .save_mcp_tool_states(&project, ®istered.name, &tools)?; + if let Some(args) = &extra_args { + state + .store + .save_project_mcp_args(&project, ®istered.name, args)?; + } for header in registered_headers { let at = SecretRef { project: &project, diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index 0fb9c5b..afc667c 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -10322,26 +10322,222 @@ async fn a_stdio_mcp_server_is_added_edited_and_deleted_through_the_settings_pag assert!(dashboard.store.mcp_server("playwright").unwrap().is_none()); } -#[tokio::test] -async fn a_stdio_mcp_server_is_not_checked_and_has_no_project_page_yet() { - let dashboard = dashboard(); +fn add_playwright(dashboard: &Dashboard) { dashboard .store .create_mcp_server_with( "playwright", &factory_server::McpTransport::Stdio { command: "npx".to_owned(), - args: Vec::new(), + args: vec!["-y".to_owned(), "@playwright/mcp@0.0.83".to_owned()], }, ) .unwrap(); +} + +#[tokio::test] +async fn a_stdio_mcp_server_is_not_checked() { + let dashboard = dashboard(); + add_playwright(&dashboard); let check = dashboard .post("/settings/projects/maestro/mcp/playwright/check", "") .await; assert_eq!(check.status, StatusCode::BAD_REQUEST); assert_eq!(dashboard.checker.calls(), 0); +} + +#[tokio::test] +async fn a_projects_page_for_a_stdio_server_has_extra_arguments_and_no_remote_parts() { + let dashboard = dashboard(); + add_playwright(&dashboard); + let page = dashboard + .get("/settings/projects/maestro/mcp/playwright") + .await; + assert_eq!(page.status, StatusCode::OK); + assert!(page.body.contains("name=\"mcp.playwright.enabled\"")); + for stage in ["clarify", "spec", "plan", "implement", "review"] { + assert!( + page.body + .contains(&format!("name=\"mcp.playwright.stage.{stage}\"")) + ); + } + assert!(page.body.contains("Extra arguments")); + assert!(page.body.contains("name=\"arg\"")); + assert!(page.body.contains("@playwright/mcp@0.0.83")); + assert!(!page.body.contains("Refresh connection")); + assert!(!page.body.contains("mcp-tools")); + assert!(!page.body.contains(".header.")); let project = dashboard.get("/settings/projects/maestro").await; - assert!(!project.body.contains("playwright")); + assert!(project.body.contains("playwright")); + assert!(project.body.contains("name=\"mcp.playwright.pipeline\"")); +} + +#[tokio::test] +async fn a_remote_servers_project_page_has_no_extra_arguments() { + let dashboard = dashboard(); + add_context7(&dashboard).await; + let page = dashboard + .get("/settings/projects/maestro/mcp/context7") + .await; + assert!(!page.body.contains("Extra arguments")); + assert!(!page.body.contains("name=\"arg\"")); + let reply = dashboard + .post( + "/settings/projects/maestro/mcp/context7", + "mcp.context7.enabled=on&mcp.context7.stage.spec=on&arg=--headless", + ) + .await; + assert_eq!(reply.status, StatusCode::OK); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "context7") + .unwrap(), + Vec::::new() + ); +} + +#[tokio::test] +async fn extra_arguments_are_saved_in_order_and_shown_in_the_command_line() { + let dashboard = dashboard(); + add_playwright(&dashboard); + let uri = "/settings/projects/maestro/mcp/playwright"; + let saved = dashboard + .post( + uri, + "mcp.playwright.enabled=on&mcp.playwright.stage.implement=on\ + &arg=--headless&arg=&arg=--viewport-size%3D1280x720&arg=a+b", + ) + .await; + assert_eq!(saved.status, StatusCode::OK); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "playwright") + .unwrap(), + ["--headless", "--viewport-size=1280x720", "a b"] + ); + let page = dashboard.get(uri).await.body; + assert!( + page.contains("npx -y @playwright/mcp@0.0.83 --headless --viewport-size=1280x720 'a b'") + ); + + // Off keeps the list. + dashboard.post(uri, "arg=--headless").await; + assert!( + !dashboard + .store + .project_mcp("maestro", "playwright") + .unwrap() + .enabled + ); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "playwright") + .unwrap(), + ["--headless"] + ); +} + +#[tokio::test] +async fn bad_extra_arguments_are_a_bad_request_that_writes_nothing() { + let dashboard = dashboard(); + add_playwright(&dashboard); + let uri = "/settings/projects/maestro/mcp/playwright"; + dashboard + .post( + uri, + "mcp.playwright.enabled=on&mcp.playwright.stage.spec=on&arg=--keep", + ) + .await; + let many: String = "&arg=a".repeat(65); + for extra in [ + many.as_str(), + "&arg=%24%7BHOME%7D", + "&arg=a%00b", + "&arg_escaped=a%5Cx", + ] { + let reply = dashboard + .post( + uri, + &format!("mcp.playwright.enabled=on&mcp.playwright.stage.plan=on{extra}"), + ) + .await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST, "{extra}"); + } + let stored = dashboard + .store + .project_mcp("maestro", "playwright") + .unwrap(); + assert!(stored.stages.spec && !stored.stages.plan); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "playwright") + .unwrap(), + ["--keep"] + ); +} + +#[tokio::test] +async fn a_pipeline_save_leaves_extra_arguments_alone() { + let dashboard = dashboard(); + add_playwright(&dashboard); + dashboard + .post( + "/settings/projects/maestro/mcp/playwright", + "mcp.playwright.enabled=on&mcp.playwright.stage.spec=on&arg=--headless", + ) + .await; + dashboard + .post( + "/settings/projects/maestro", + "clarify=&spec=&plan=&implement=&review=&gates=on\ + &mcp.playwright.pipeline=on&mcp.playwright.stage.implement=on", + ) + .await; + let stored = dashboard + .store + .project_mcp("maestro", "playwright") + .unwrap(); + assert!(stored.enabled && stored.stages.implement && !stored.stages.spec); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "playwright") + .unwrap(), + ["--headless"] + ); +} + +#[tokio::test] +async fn a_collaborator_of_another_project_gets_404_on_a_stdio_servers_page() { + let dashboard = two_projects(); + add_playwright(&dashboard); + dashboard + .store + .add_collaborator("tool", STRANGER, "test") + .unwrap(); + let uri = "/settings/projects/maestro/mcp/playwright"; + assert_eq!( + dashboard.get_as(STRANGER, uri).await.status, + StatusCode::NOT_FOUND + ); + assert_eq!( + dashboard + .post_as(STRANGER, uri, "arg=--headless") + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!( + dashboard + .store + .project_mcp_args("maestro", "playwright") + .unwrap(), + Vec::::new() + ); } #[tokio::test] diff --git a/crates/factory-server/tests/mcp.rs b/crates/factory-server/tests/mcp.rs index 88d14f8..6615413 100644 --- a/crates/factory-server/tests/mcp.rs +++ b/crates/factory-server/tests/mcp.rs @@ -698,3 +698,116 @@ fn a_database_from_before_stdio_loads_every_server_as_remote() { .create_mcp_server_with("playwright", &stdio("npx", &[])) .unwrap(); } + +fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() +} + +fn stdio_store() -> Arc { + let store = store(); + store + .create_mcp_server_with( + "playwright", + &McpTransport::Stdio { + command: "npx".to_owned(), + args: strings(&["-y", "pkg"]), + }, + ) + .expect("create"); + store +} + +#[test] +fn project_mcp_args_keep_order_and_default_to_empty() { + let store = stdio_store(); + assert_eq!( + store.project_mcp_args("maestro", "playwright").unwrap(), + Vec::::new() + ); + let args = strings(&["--headless", "a b", "--x=1"]); + store + .save_project_mcp_args("maestro", "playwright", &args) + .unwrap(); + assert_eq!( + store.project_mcp_args("maestro", "playwright").unwrap(), + args + ); +} + +#[test] +fn saving_one_projects_args_leaves_other_projects_alone() { + let store = stdio_store(); + store + .save_project_mcp_args("maestro", "playwright", &strings(&["--headless"])) + .unwrap(); + store + .save_project_mcp_args("tool", "playwright", &strings(&["--caps=vision"])) + .unwrap(); + store + .save_project_mcp_args("maestro", "playwright", &strings(&["--x=1"])) + .unwrap(); + assert_eq!( + store.project_mcp_args("tool", "playwright").unwrap(), + ["--caps=vision"] + ); +} + +#[test] +fn turning_a_server_off_keeps_the_args() { + let store = stdio_store(); + let on = McpProjectSettings { + enabled: true, + stages: only("implement"), + }; + store + .save_project_mcp("maestro", "playwright", &on) + .unwrap(); + store + .save_project_mcp_args("maestro", "playwright", &strings(&["--headless"])) + .unwrap(); + store + .save_project_mcp("maestro", "playwright", &McpProjectSettings::default()) + .unwrap(); + store + .save_project_mcp("maestro", "playwright", &on) + .unwrap(); + assert_eq!( + store.project_mcp_args("maestro", "playwright").unwrap(), + ["--headless"] + ); +} + +#[test] +fn deleting_a_server_or_removing_a_project_deletes_its_args() { + let store = stdio_store(); + store + .create_project( + "maestro", + factory_runner::ForgeKind::GitHub, + "o/m", + "main", + None, + Some("alice"), + ) + .unwrap(); + store + .save_project_mcp_args("maestro", "playwright", &strings(&["--a"])) + .unwrap(); + store + .save_project_mcp_args("tool", "playwright", &strings(&["--b"])) + .unwrap(); + store.remove_project("maestro").unwrap(); + assert_eq!( + store.project_mcp_args("maestro", "playwright").unwrap(), + Vec::::new() + ); + assert_eq!( + store.project_mcp_args("tool", "playwright").unwrap(), + ["--b"] + ); + store.delete_mcp_server("playwright").unwrap(); + assert_eq!( + store.project_mcp_args("tool", "playwright").unwrap(), + Vec::::new() + ); +} diff --git a/docs/design.md b/docs/design.md index 887a1c9..798917e 100644 --- a/docs/design.md +++ b/docs/design.md @@ -31,16 +31,16 @@ 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. | +| 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 it 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 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. | +| 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 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. | +| 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. | | 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. | +| 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. | | Renovate pull request jobs | A Renovate job is a `Job` with `kind` `Renovate(RenovatePr)`, at its own `Stage::Renovate` with the request text set to the pull request title. A job stored before `kind` existed loads as `Request`. It skips clarify, spec, plan, implement and publish. The factory watches the pull request, and the core decides everything from what each watch reports. `Event::RenovateObserved` carries the head commit, the CI state (`NoChecks`, `Pending`, `Failed` with the log, or `Passed` with the diff and description when the job has no verdict for that head), the retry limits, the project's auto-merge flag and the project account's access (`RenovateAccess`: whether it may rerun CI, whether it may merge, and its login; a job stored before this loads with full access). The factory holds the limits and passes them in on every observation, so a saved limit reaches a job in flight with no restart and the job stores only its counts. A different head resets the reruns, the automatic reruns, the stop and the verdict. A failed observation checks the total first: at or above the total the job queues the stopped comment, which names the rerun count, and stops. Below it, the job reruns with no agent until the automatic reruns are used up, then runs `Task::AnalyzeFailure`. A transient verdict reruns and counts toward the total only. With Read access the factory makes no rerun call: a failed head goes straight to `Task::AnalyzeFailure` and a transient verdict queues a `TransientNoWrite` comment, which says the failure looks transient and that the project account needs Write to rerun CI, and stops until a new head or Retry. The executor reads the account's access with `Forge::access` and `Forge::may_merge` on every watch, so granting Write takes effect on the next head with no restart, and a failed read fails the watch so the scheduler retries. A caused-by-update verdict queues a comment with the reason and stops. A passed observation with no verdict for the head runs `Task::CheckDiff`. With a safe verdict, auto-merge on queues `Command::MergeRenovate`, which approves and merges only that head, unless the account may not merge (Read access, or a forge that refuses it), when the job waits as ready to merge and the job page names the account and the access it needs, and auto-merge off waits as ready to merge and merges on a later watch once the switch is on. An unsafe verdict queues a comment and waits. `NoChecks` and `Pending` change nothing, so a pull request with no checks never merges. A comment is a factory turn with `Command::PostComment`, answered by `Event::Commented`, and a `(head, kind)` pair is recorded so each kind posts once per head. A stopped or unsafe job waits at `Ask::Renovate` and keeps a watch-only command, so it still sees a merge, a close or a new head. A ready job keeps the full watch. Limits and the auto-merge switch arrive on every watch and core applies them. `Store::apply_in` writes no `job_events` row and does not rewrite the job for an `Event::RenovateObserved` that leaves the job equal, because every look would otherwise change the job's notification key. A change those settings cause, such as a merge or a stop, is recorded. `Event::Retry` on a stopped job resets both counts. When the stored access may rerun CI it reruns without counting that rerun. When it may not (Read), Retry returns the job to the factory turn, so a fresh watch reads the current head, CI and access and decides again. The executor checks the access of the credential it resolves before each Renovate rerun, approval and merge (an agent-requested rerun in a request job is not checked), because a collaborator may replace the token after the watch. A denied rerun returns `Event::RerunDenied`, which returns the job to the factory turn for a fresh watch, so Retry on a Read account goes to the failure analysis and not to a rerun. A denied approval or merge returns the job to watching and the executor makes no write call. The denial error starts with `NOT_PERMITTED`, and the scheduler treats it as a denial and not a retryable failure. `Event::Merged` ends in `merged` and `Event::ClosedUnmerged` in `cancelled`, which is Done and sends no notification. The comment bodies are plain text from the project account. A Renovate job has the requester `factory`, so every operation of it, and the discovery that creates it, runs as the project token. A project with Renovate on and no project token is skipped by discovery with a logged warning. The diff verdict records `from` and `to`, the upstream refs the bump moves between when the diff shows them, because the packaging analysis fetches the upstream build config changes between them. Each of the two runs starts a fresh session under `Session::Renovate` and uses the review stage's agent, model, effort and MCP servers. The worker gets the log or the diff in its prompt and no GitHub token. Discovery: on each pass the scheduler lists, for each project with "Renovate pull requests" on, the open pull requests against the project's base branch that `renovate[bot]` or `renovate` opened, at most once per 5 minutes per project, which keeps it under the spec's 10 minutes. The last listing time per project lives in memory, so a restart lists again at once. A project with the switch off gets no listing call. `create_renovate_job` inserts the job and a `renovate_prs (project, number, job_id)` row in one transaction and does nothing when the pair exists, so a pull request gets one job across restarts, even after the job finishes and expires. Job expiry leaves the table alone and `remove_project` deletes its rows. The job's requester is `factory`, because the factory made it, see Job board. The scheduler reads the retry limits from `Settings` and the project's auto-merge flag on every watch and passes them to the executor, which builds `RenovateObserved`. The executor reads the pull request status with the project token, fetches the failure log only for a failed head and the diff only for a passed head with no verdict, and reports a merge or close at once. A watch-only look reports nothing while the head is the one the job already has. A merge approves the checked head with a plain review text and then squash-merges only that head, so a commit pushed after the watch is never approved. GitHub may still accept a review of an older commit that stays in the pull request, and the merge, guarded by the head SHA, is what refuses a moved head. A refused approval or merge returns the job to watching, so the next look sees the current head or a merge or close by a person. A rerun that finds no failed Actions run changes no count and stops triage with a comment, because a rerun that never happened must not use up the limit. A rerun of a Renovate job logs "Rerunning CI" and not that the agent asked. Discovery passes the stored Renovate account to `Forge::renovate_prs` for a Salsa project and `None` for GitHub. With `None` the forge keeps `renovate[bot]` and `renovate`. With a name the GitLab forge lists open merge requests with `author_username` and `target_branch` set to the base. | | Fix job for a stopped Renovate job | A stopped Renovate job can hand its stop to a fix job, a normal job built by `Job::fix` with `JobKind::Fix { source_job, source_pr }` and a request text from `RenovatePr::fix_request`. `RenovatePr::fix` holds a `FixLink` with the fix job's id, the reason the job showed when the fix started, and a `FixState`, `Running` or `Merged` with the head at the merge and a `RebaseState` of `Pending`, `Requested` or `Failed`. A job stored without `fix` loads with none. `Event::FixStarted` applies only at the stopped wait and only when no fix runs, so a double submit creates one fix job. The job then waits as `RenovateWait::Fixing`, which keeps the watch-only command and offers no Retry, and a new head keeps a running fix. The scheduler reads a running fix job on every watch of the Renovate job, before the executor watch, because a watch-only look at the same head returns nothing. It reports `Event::FixEnded` with `Merged` for a merged stage with a numbered pull request, `Closed` for a merged stage with none and for a non-retryable failure whose reason is that the pull request closed without merging, `Cancelled` for a cancelled stage, `Dismissed` for a dismissed failure, and `Deleted` for a missing job or one whose `fix_source` is not this job and pull request, since ids may be reused. A merge carries the head the pull request had at the merge, not the last polled head. The scheduler asks the forge when the fix pull requests merged (`mergedAt`) and weighs the evidence about the current head in order: the time GitHub recorded the force push that set it decides; a commit made after the merge became the head after it; and a head the factory saw before the merge (`renovate_heads` keeps when it first saw each head) was the head by then. A head that became the head after the merge is a new head, so the empty head asks for no rebase and the factory records `RebaseSkipped`. A plain push has no date on GitHub and a commit date only bounds it from below, so a head with none of that evidence is unknown, not dated by its commit: the scheduler reports `FixOutcome::MergedUnordered` with the real head, and the job goes to Needs you with the hand-rebase message and keeps that head as its watch baseline, so watching the same head again changes nothing and only a later head restarts triage. A timeline that lacks the head's commit node still counts: the commit date is optional and the force-push event or the first-seen evidence decides. The factory's own record of the merge is not used, because it lags the real merge. A failed fix job that is not dismissed reports nothing, so the Renovate job keeps waiting while the fix job is retried from its own page. The core ignores it unless the id matches a running fix, and the store writes no `job_events` row when it leaves the job equal, so a repeated report adds none. `Store::start_fix` creates the fix job with the clicking login as requester and applies `FixStarted` in one transaction, so core's rejection of a second start rolls the new job back. A merged fix carries `head` in `FixOutcome::Merged`, the Renovate head when the fix merged, because the last head the job observed may be older or newer. After the rebase result, that head is the baseline for the next observation. The core queues one `Command::RequestRebase` for that head. `Executor::request_rebase` runs in the server process with the account that resolves for the Renovate job, like `merge_renovate`, so the worker gets no token. It reads the pull request and returns `Rebase::HeadMoved` when the head differs, and otherwise ticks the checkbox and returns `Requested` or `NoCheckbox`. The scheduler maps those to `RebaseRequested`, `RebaseSkipped` and `RebaseFailed`, and a failed write becomes `RebaseFailed` with gh's message, with no retry. The forge call takes the expected head and compares it with the head in the same read as the description, and `Store::claim_rebase` records the request in `rebase_claims` before the write, and the store grants the claim only while the job still owes a pending rebase for that fix and head, in the same transaction that inserts it, and only while the job's own `next_command()` is still that `RequestRebase`, so neither a stale command nor a cancelled job claims. A stored result or a new fix retires the claims of the Renovate job, so an old claim never blocks a later fix that reuses the id. A restart that finds the claim without a result writes nothing and reports `RebaseFailed`, since the write may have happened, so the request happens at most once per fix job. `Event::RebaseRequested` goes back to `Fixing`, `Event::RebaseSkipped` clears the fix, and `Event::RebaseFailed` waits as `RenovateWait::RebaseFailed` with the hand-rebase message. Any other ending returns the job to `Stopped`, with the newest stop reason or else the reason saved on the link, plus a line that names the fix job. It does so from the `Fixing` wait and from a factory turn on a new head. A new head after a merged fix clears the fix and starts triage from zero. The fix events store as `fix-started`, `fix-ended`, `rebase-requested`, `rebase-skipped` and `rebase-failed`. The Triage stopped card of a Renovate job shows an instructions textarea and a "Fix in a separate pull request" button next to Retry, and no other wait shows them. The form posts to `POST /jobs/{id}/fix` behind the same project collaborator check as Retry and a CSRF check with `require_csrf`, because the post creates a job. The form carries a token bound to the login, on the full page and on the polled fragment, and a missing or invalid token answers 403 and creates nothing. The page links to the fix job and back only after it checks that the stored job is still in the same project and still has the matching `fix_source` or pull request number, as it does for gap jobs, since SQLite reuses ids, and it shows plain text otherwise. The stopped reason and the line that names the fix job render on separate lines, and an empty instruction counts as none. A rejected second start answers 409. The `Fixing` wait renders "Waiting for fix job #N" with `#N` as a same-tab link and no buttons. It sits in the Factory lane, so the job is in Running and `GET /notifications` lists nothing for it, while `RebaseFailed` stays in Needs you. The Renovate job page lists its fix job, and the fix job page links back to the Renovate job. The timeline has no step for the `renovate` stage, so the fix and rebase events show as a list under the steps. `fix-started` stores the fix job's id, `fix-ended` the id and how it ended, and `rebase-failed` the reason. | diff --git a/e2e/tests/project-settings.spec.ts b/e2e/tests/project-settings.spec.ts index e226602..8a075c5 100644 --- a/e2e/tests/project-settings.spec.ts +++ b/e2e/tests/project-settings.spec.ts @@ -675,3 +675,61 @@ mcpTest('a login that is not a collaborator gets the 404 page for a project MCP expect(response?.status()).toBe(404); await expect(page.getByText(`no project ${mcpProject}`)).toBeVisible(); }); + +test('a stdio MCP server takes extra arguments, keeps them when off and shows in the pipeline', async ({ + page, + project, +}) => { + const server = `pw-${Math.random().toString(36).slice(2, 8)}`; + const added = await page.request.post('/settings/mcp', { + form: { name: server, kind: 'stdio', command: 'playwright-mcp', arg: '--no-sandbox' }, + maxRedirects: 0, + }); + expect(added.status()).toBeLessThan(400); + const path = `/settings/projects/${project}/mcp/${server}`; + const enable = page.getByLabel(`Run this server for ${project}`); + const args = page.getByLabel('Argument'); + const line = page.locator('.mcp-command-line'); + + await page.goto(settingsPath(project)); + await expect(page.locator('.server-row').filter({ hasText: server })).toContainText('Off'); + await page.getByRole('link', { name: 'Configure' }).click(); + await expect(page).toHaveURL(path); + await expect(page.getByRole('button', { name: 'Refresh connection' })).toHaveCount(0); + await expect(page.locator('.mcp-tool')).toHaveCount(0); + await expect(page.getByText('so the factory cannot check its connection')).toBeVisible(); + await expect(line).toHaveText('playwright-mcp --no-sandbox'); + + await enable.check(); + await page.getByRole('checkbox', { name: 'implement', exact: true }).check(); + await args.nth(0).fill('--headless'); + await page.getByRole('button', { name: 'Add argument' }).click(); + await args.last().fill('--viewport-size=1280x720'); + await args.nth(1).fill('--junk'); + await page.getByRole('button', { name: 'Remove' }).nth(1).click(); + await expect(page.getByText('Unsaved changes.')).toBeVisible(); + await page.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(page.getByText('Saved.', { exact: true })).toBeVisible(); + + await page.goto(path); + await expect(args.nth(0)).toHaveValue('--headless'); + await expect(args.nth(1)).toHaveValue('--viewport-size=1280x720'); + await expect(line).toHaveText('playwright-mcp --no-sandbox --headless --viewport-size=1280x720'); + + await enable.uncheck(); + await page.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(page.getByText('Saved.', { exact: true })).toBeVisible(); + await enable.check(); + await page.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(page.getByText('Saved.', { exact: true })).toBeVisible(); + await expect(args.nth(1)).toHaveValue('--viewport-size=1280x720'); + + await page.goto(settingsPath(project, '?stage=spec')); + const specBox = panel(page, 'spec').getByRole('checkbox', { name: server }); + await specBox.check(); + await page.getByRole('button', { name: `Save ${project}` }).click(); + await expect(page.getByText('Saved.', { exact: true })).toBeVisible(); + await page.goto(path); + await expect(page.getByRole('checkbox', { name: 'spec', exact: true })).toBeChecked(); + await expect(args.nth(1)).toHaveValue('--viewport-size=1280x720'); +}); From 9093f39ce8562661e6a8075ab770170e07e5c7b5 Mon Sep 17 00:00:00 2001 From: moonthebot <289833623+moonthebot@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:05:25 +0000 Subject: [PATCH 2/2] factory-server: mcp: address review of stdio arguments Decode extra arguments only for a stdio server, fail on a malformed stored list, show whitespace in the command line preview, and say that saved arguments take effect once worker support lands. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- crates/factory-server/src/pages.rs | 14 +++++++++----- crates/factory-server/src/store.rs | 11 ++++++----- crates/factory-server/src/web.rs | 14 +++++++------- crates/factory-server/static/style.css | 1 + crates/factory-server/tests/dashboard.rs | 3 +-- docs/design.md | 2 +- e2e/tests/project-settings.spec.ts | 5 ++++- 7 files changed, 29 insertions(+), 21 deletions(-) diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index bbebb7f..a2845b4 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -2313,9 +2313,6 @@ pub fn settings_project_mcp( ) } -/// The part of a stdio server's project block below the stage checkboxes: the -/// command and base arguments read-only, the project's extra arguments, and the -/// command line a run starts. fn stdio_block(stdio: &StdioSettings) -> Markup { let line = std::iter::once(&stdio.command) .chain(&stdio.args) @@ -2349,7 +2346,7 @@ fn stdio_block(stdio: &StdioSettings) -> Markup { } template { (arg_row("")) } button.add-arg type="button" { "Add argument" } - p.hint { "Appended after the server's own arguments, in this order, for this project's runs only. The agent can read them, so no secret belongs here. An argument is passed as one value, with no shell splitting, and may not contain ${. A change applies at the job's next run." } + p.hint { "Appended after the server's own arguments, in this order, for this project's runs only. The agent can read them, so no secret belongs here. An argument is passed as one value, with no shell splitting, and may not contain ${. Runs do not start stdio servers yet, so a saved list takes effect once worker support lands." } } div.field { span.label { "Command line a run starts" } @@ -2359,8 +2356,15 @@ fn stdio_block(stdio: &StdioSettings) -> Markup { } } -/// `part` as a shell word, so the preview shows where one argument ends. fn shell_quote(part: &str) -> String { + if part.contains(['\r', '\n']) { + let escaped = part + .replace('\\', "\\\\") + .replace('\'', "\\'") + .replace('\r', "\\r") + .replace('\n', "\\n"); + return format!("$'{escaped}'"); + } let plain = !part.is_empty() && part .bytes() diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index bd14d39..bf04819 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -4458,11 +4458,11 @@ impl Store { } /// The extra arguments `project` appends after the base arguments of the - /// stdio server `server`, in order. Empty when none are stored. + /// stdio server `server`, in order. Empty when no row is stored. /// /// # Errors /// - /// Fails on a database error. + /// Fails on a database error or when the stored list is not valid JSON. pub fn project_mcp_args(&self, project: &str, server: &str) -> Result, StoreError> { let stored: Option = self .conn() @@ -4472,9 +4472,10 @@ impl Store { |row| row.get(0), ) .optional()?; - Ok(stored - .and_then(|json| serde_json::from_str(&json).ok()) - .unwrap_or_default()) + match stored { + Some(json) => Ok(serde_json::from_str(&json)?), + None => Ok(Vec::new()), + } } /// Saves `project`'s extra arguments for `server`, writing only this row. diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 54fc9fa..d9a6218 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -3383,14 +3383,14 @@ async fn save_project_mcp( Form(pairs): Form>, ) -> Result { let registered = project_and_server(&state, &headers, &project, &server)?; - // The extra arguments are a repeated field, which the map below would - // collapse, so they are read from the pairs in order. let mut extra_args = Vec::new(); - for (key, value) in &pairs { - match key.as_str() { - "arg" => extra_args.push(value.clone()), - "arg_escaped" => extra_args.push(unescape_arg(value)?), - _ => {} + if registered.as_stdio().is_some() { + for (key, value) in &pairs { + match key.as_str() { + "arg" => extra_args.push(value.clone()), + "arg_escaped" => extra_args.push(unescape_arg(value)?), + _ => {} + } } } let form = ProjectForm(pairs.into_iter().collect()); diff --git a/crates/factory-server/static/style.css b/crates/factory-server/static/style.css index 45dc0b3..559b0fb 100644 --- a/crates/factory-server/static/style.css +++ b/crates/factory-server/static/style.css @@ -420,6 +420,7 @@ select:focus, textarea:focus, button:focus-visible { outline: var(--focus-ring); .field > .label { display: block; font-weight: var(--weight-semibold); margin: 0 0 var(--space-6); } .mcp-header-row, .mcp-arg-row { display: flex; gap: var(--space-8); align-items: center; margin-bottom: var(--space-8); } .mcp-header-row > .grow, .mcp-arg-row > .grow { flex: 1 1 auto; } +.mcp-command-line { white-space: pre-wrap; overflow-wrap: anywhere; } .mcp-headers + .add-header, .mcp-args + .add-arg { margin-bottom: var(--space-6); } .kind-choice { border: 0; padding: 0; margin: 0 0 var(--space-14); } .kind-choice label { margin-right: var(--space-14); } diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index afc667c..ec2fc9d 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -10384,7 +10384,7 @@ async fn a_remote_servers_project_page_has_no_extra_arguments() { let reply = dashboard .post( "/settings/projects/maestro/mcp/context7", - "mcp.context7.enabled=on&mcp.context7.stage.spec=on&arg=--headless", + "mcp.context7.enabled=on&mcp.context7.stage.spec=on&arg=--headless&arg_escaped=a%5Cx", ) .await; assert_eq!(reply.status, StatusCode::OK); @@ -10422,7 +10422,6 @@ async fn extra_arguments_are_saved_in_order_and_shown_in_the_command_line() { page.contains("npx -y @playwright/mcp@0.0.83 --headless --viewport-size=1280x720 'a b'") ); - // Off keeps the list. dashboard.post(uri, "arg=--headless").await; assert!( !dashboard diff --git a/docs/design.md b/docs/design.md index 798917e..f755830 100644 --- a/docs/design.md +++ b/docs/design.md @@ -31,7 +31,7 @@ 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. The scheduler reads it 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. 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. | diff --git a/e2e/tests/project-settings.spec.ts b/e2e/tests/project-settings.spec.ts index 8a075c5..6b757cb 100644 --- a/e2e/tests/project-settings.spec.ts +++ b/e2e/tests/project-settings.spec.ts @@ -707,6 +707,8 @@ test('a stdio MCP server takes extra arguments, keeps them when off and shows in await args.last().fill('--viewport-size=1280x720'); await args.nth(1).fill('--junk'); await page.getByRole('button', { name: 'Remove' }).nth(1).click(); + await page.getByRole('button', { name: 'Add argument' }).click(); + await args.last().fill('a b'); await expect(page.getByText('Unsaved changes.')).toBeVisible(); await page.getByRole('button', { name: 'Save', exact: true }).click(); await expect(page.getByText('Saved.', { exact: true })).toBeVisible(); @@ -714,7 +716,8 @@ test('a stdio MCP server takes extra arguments, keeps them when off and shows in await page.goto(path); await expect(args.nth(0)).toHaveValue('--headless'); await expect(args.nth(1)).toHaveValue('--viewport-size=1280x720'); - await expect(line).toHaveText('playwright-mcp --no-sandbox --headless --viewport-size=1280x720'); + await expect(line).toHaveText("playwright-mcp --no-sandbox --headless --viewport-size=1280x720 'a b'"); + expect(await line.evaluate((el) => getComputedStyle(el).whiteSpace)).toBe('pre-wrap'); await enable.uncheck(); await page.getByRole('button', { name: 'Save', exact: true }).click();