diff --git a/crates/factory-server/src/lib.rs b/crates/factory-server/src/lib.rs index 12fd3cbe..1a9ee346 100644 --- a/crates/factory-server/src/lib.rs +++ b/crates/factory-server/src/lib.rs @@ -45,7 +45,9 @@ pub use github::{ check_repo, }; pub use gitlab::GlabRepos; -pub use mcp::{McpError, McpProjectSettings, McpServer, McpStages, McpTool, McpToolState}; +pub use mcp::{ + McpError, McpProjectSettings, McpServer, McpStages, McpTool, McpToolState, McpTransport, +}; pub use podman::PodmanExecutor; pub use projects::{ ImportError, Project, ProjectForge, Projects, StageAgents, StageEfforts, StageModels, diff --git a/crates/factory-server/src/mcp.rs b/crates/factory-server/src/mcp.rs index 86fd30e1..c67c2617 100644 --- a/crates/factory-server/src/mcp.rs +++ b/crates/factory-server/src/mcp.rs @@ -1,8 +1,10 @@ -//! The MCP server registry: the remote servers an operator adds on the -//! settings page, and the validation their fields must pass. +//! The MCP server registry: the servers an operator adds on the settings page, +//! and the validation their fields must pass. //! -//! A server is a name, an `https` URL and a list of header names each project -//! may fill with a value of its own. The name is the key in a run's MCP config +//! A server is a name and a transport. A remote server is an `https` URL and a +//! list of header names each project may fill with a value of its own. A stdio +//! server is a command and base arguments the agent starts inside the worker. +//! The name is the key in a run's MCP config //! and part of the proxy path, so it is a tight slug. The header names are the //! only headers a project may set, so the factory refuses the ones it sets //! itself or that the streamable-HTTP protocol owns. The [`Store`](crate::Store) @@ -46,6 +48,26 @@ pub enum McpTransport { /// is a valid HTTP token and not reserved; no two differ only in case. headers: Vec, }, + /// A process the agent starts inside the worker and talks to over stdin + /// and stdout. It bypasses the proxy, so it has no stored values. + Stdio { + /// The program to run, found on the worker's `PATH`. Trimmed. + command: String, + /// The base arguments, in order, each one argv element. Kept as typed: + /// not trimmed, never split or expanded by a shell. + args: Vec, + }, +} + +impl McpTransport { + /// The kind's name as the registry stores it and the pages show it. + #[must_use] + pub fn kind(&self) -> &'static str { + match self { + McpTransport::Remote { .. } => "remote", + McpTransport::Stdio { .. } => "stdio", + } + } } impl McpServer { @@ -60,11 +82,32 @@ impl McpServer { } } + #[must_use] + pub fn stdio(name: impl Into, command: impl Into, args: Vec) -> Self { + Self { + name: name.into(), + transport: McpTransport::Stdio { + command: command.into(), + args, + }, + } + } + /// The URL and header names when the server is remote. #[must_use] pub fn as_remote(&self) -> Option<(&str, &[String])> { match &self.transport { McpTransport::Remote { url, headers } => Some((url, headers)), + McpTransport::Stdio { .. } => None, + } + } + + /// The command and base arguments when the server is stdio. + #[must_use] + pub fn as_stdio(&self) -> Option<(&str, &[String])> { + match &self.transport { + McpTransport::Stdio { command, args } => Some((command, args)), + McpTransport::Remote { .. } => None, } } } @@ -144,6 +187,16 @@ pub enum McpError { ReservedHeader(String), /// A project enabled a server without picking a stage for it. NoStage(String), + /// A stdio server's command is empty, too long, or has a NUL, a newline or + /// `${`. + BadCommand(String), + /// An argument list has too many entries, or an entry that is too long or + /// has a NUL or `${`. + BadArgs(String), + /// A posted kind is neither `remote` nor `stdio`. + BadKind(String), + /// An edit would change a server's kind, which is fixed when it is added. + KindChange(String), Store(StoreError), } @@ -156,7 +209,12 @@ impl fmt::Display for McpError { ), McpError::DuplicateName(name) => write!(f, "a server named {name:?} already exists"), McpError::NotFound(name) => write!(f, "no MCP server named {name:?}"), - McpError::BadUrl(reason) => write!(f, "{reason}"), + McpError::BadUrl(reason) + | McpError::BadCommand(reason) + | McpError::BadArgs(reason) + | McpError::BadKind(reason) => { + write!(f, "{reason}") + } McpError::BadHeader(header) => { write!(f, "{header:?} is not a valid HTTP header name") } @@ -168,6 +226,10 @@ impl fmt::Display for McpError { f, "the server {server:?} is enabled but no stage is checked; pick at least one or turn it off" ), + McpError::KindChange(name) => write!( + f, + "the server {name:?} cannot change kind; delete it and add it again" + ), McpError::Store(err) => write!(f, "{err}"), } } @@ -237,6 +299,82 @@ pub(crate) fn validate_url(url: &str) -> Result<(), McpError> { Ok(()) } +/// The longest stdio command, in bytes. +const MAX_COMMAND_BYTES: usize = 256; +/// The most arguments one list may hold. +pub(crate) const MAX_ARGS: usize = 64; +/// The longest single argument, in bytes. +pub(crate) const MAX_ARG_BYTES: usize = 4096; + +/// Checks a stdio server's command and base arguments and returns them as the +/// registry stores them: the command trimmed and the empty arguments dropped. +/// +/// `${` is refused because Copilot expands `${NAME}` in the command and +/// arguments of its MCP config and the other agents do not, so refusing it +/// keeps one entry meaning the same on all three. +/// +/// # Errors +/// +/// Returns [`McpError::BadCommand`] or [`McpError::BadArgs`] naming the problem. +pub(crate) fn validate_stdio( + command: &str, + args: &[String], +) -> Result<(String, Vec), McpError> { + if command.contains(['\n', '\r']) { + return Err(McpError::BadCommand( + "the command has a line break".to_owned(), + )); + } + let command = command.trim(); + let bad = |reason: &str| Err(McpError::BadCommand(format!("the command {reason}"))); + if command.is_empty() { + return bad("is empty"); + } + if command.len() > MAX_COMMAND_BYTES { + return bad(&format!("is longer than {MAX_COMMAND_BYTES} bytes")); + } + if command.contains('\0') { + return bad("has a NUL"); + } + if command.contains("${") { + return bad("contains \"${\", which Copilot would expand"); + } + Ok((command.to_owned(), validate_args(args)?)) +} + +/// Drops the empty arguments and checks the rest: at most 64, each at most +/// 4096 bytes, with no NUL or `${`. A line break is allowed. Order is kept and no +/// argument is trimmed, so spaces, quotes and a lone `$` arrive unchanged. +/// +/// # Errors +/// +/// Returns [`McpError::BadArgs`] naming the problem. +pub(crate) fn validate_args(args: &[String]) -> Result, McpError> { + let kept: Vec = args.iter().filter(|arg| !arg.is_empty()).cloned().collect(); + if kept.len() > MAX_ARGS { + return Err(McpError::BadArgs(format!( + "there are {} arguments; the most allowed is {MAX_ARGS}", + kept.len() + ))); + } + for arg in &kept { + if arg.len() > MAX_ARG_BYTES { + return Err(McpError::BadArgs(format!( + "an argument is longer than {MAX_ARG_BYTES} bytes" + ))); + } + if arg.contains('\0') { + return Err(McpError::BadArgs("an argument contains a NUL".to_owned())); + } + if arg.contains("${") { + return Err(McpError::BadArgs(format!( + "the argument {arg:?} contains \"${{\", which Copilot would expand" + ))); + } + } + Ok(kept) +} + /// Validates each header name and drops a case-insensitive duplicate, keeping /// the first spelling. The result is what the registry stores. /// diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index b8f24d02..fb92187a 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -31,7 +31,7 @@ const PROJECT_PICKER: &str = include_str!("../static/project-picker.js"); const ONBOARD_FORGE: &str = include_str!("../static/onboard-forge.js"); const SOURCE_LINK: &str = include_str!("../static/source-link.js"); const PASTE_IMAGES: &str = include_str!("../static/paste-images.js"); -const MCP_HEADER_ROWS: &str = include_str!("../static/mcp-header-rows.js"); +const MCP_ROWS: &str = include_str!("../static/mcp-rows.js"); const NOTIFICATIONS: &str = include_str!("../static/notifications.js"); const PERMISSION_BAR: &str = include_str!("../static/permission-bar.js"); const NOTIFICATION_PERMISSION: &str = include_str!("../static/notification-permission.js"); @@ -1669,7 +1669,7 @@ pub fn settings_mcp( &html! { h1 { "MCP servers" } (mcp_servers(servers, secrets_available)) - script { (PreEscaped(MCP_HEADER_ROWS)) } + script { (PreEscaped(MCP_ROWS)) } }, ) } @@ -1725,19 +1725,28 @@ pub fn settings_mcp_server( &html! { p.crumbs { a href="/settings/mcp" { "MCP servers" } " › " (server.name) } h1 { (server.name) } - p.meta { "Shared by every project. Each project stores its own header values on its own page." } + p.meta { "Kind: " span.server-kind { (server.transport.kind()) } } + @if server.as_stdio().is_some() { + p.meta { "Shared by every project. The command and base arguments run inside the worker of every project that turns the server on." } + } @else { + p.meta { "Shared by every project. Each project stores its own header values on its own page." } + } @if let Some(problem) = page.problem { div.card.failed { (problem) } } (mcp_server_form(server, page.pending)) - (server_usage_card(&server.name, page.usage)) + (server_usage_card(&server.name, page.usage, server.as_stdio().is_some())) form.card.danger-card method="post" action={ "/settings/mcp/" (crate::web::query_escape(&server.name)) "/delete" } { h2 { "Delete " (server.name) } - p.hint { - "Removes the server from every project and deletes the " - (stored) " stored " - (if stored == 1 { "value" } else { "values" }) - " for it. Type the server's name to confirm." + @if server.as_stdio().is_some() { + p.hint { "Removes the server from every project. Type the server's name to confirm." } + } @else { + p.hint { + "Removes the server from every project and deletes the " + (stored) " stored " + (if stored == 1 { "value" } else { "values" }) + " for it. Type the server's name to confirm." + } } div.row { input.grow type="text" name="confirm_name" aria-label="Server name" @@ -1746,7 +1755,7 @@ pub fn settings_mcp_server( button.danger { "Delete " (server.name) } } } - script { (PreEscaped(MCP_HEADER_ROWS)) } + script { (PreEscaped(MCP_ROWS)) } }, ) } @@ -1754,7 +1763,7 @@ pub fn settings_mcp_server( /// The "Used by" card: each project with whether it runs the server, in how /// many stages, and which of its header values are stored, with a link to the /// project's page for the server. -fn server_usage_card(server: &str, usage: &[ServerUsage]) -> Markup { +fn server_usage_card(server: &str, usage: &[ServerUsage], stdio: bool) -> Markup { html! { div.card { h2 { "Used by" } @@ -1766,7 +1775,9 @@ fn server_usage_card(server: &str, usage: &[ServerUsage]) -> Markup { span.server-name { (entry.project.shown) } span.hint.server-url { (usage_line(entry.enabled, entry.stages)) } (header_badges(&entry.headers)) - a.link-button href=(project_mcp_href(&entry.project.id, server)) { "Open" } + @if !stdio { + a.link-button href=(project_mcp_href(&entry.project.id, server)) { "Open" } + } } } } @@ -2285,19 +2296,20 @@ pub fn settings_project_mcp( /// button and the given `hint`. The names post as a repeated `header` field. The /// box's `pattern` refuses anything but an HTTP header name in the browser, so a /// pasted `Authorization: x` is caught before the form posts; the server -/// validates again. "Add header" and "Remove" run `MCP_HEADER_ROWS`. Without +/// validates again. "Add header" and "Remove" run `MCP_ROWS`. Without /// JavaScript the form still works: you add one name per save and remove a name /// by clearing its box. -fn header_rows(names: &[String], hint: &Markup) -> Markup { +fn header_rows(names: &[String], hint: &Markup, validate: bool) -> Markup { html! { div.field { span.label { "Header names" } div.mcp-headers { @for name in names { - (header_row(name)) + (header_row(name, validate)) } - (header_row("")) + (header_row("", validate)) } + template { (header_row("", validate)) } button.add-header type="button" { "Add header" } (hint) } @@ -2305,11 +2317,11 @@ fn header_rows(names: &[String], hint: &Markup) -> Markup { } /// One header-name row: a text box named `header` and a Remove button. -fn header_row(value: &str) -> Markup { +fn header_row(value: &str, validate: bool) -> Markup { html! { div.mcp-header-row { input.grow type="text" name="header" placeholder="Authorization" - pattern=(HEADER_NAME_PATTERN) aria-label="Header name" + pattern=[validate.then_some(HEADER_NAME_PATTERN)] aria-label="Header name" title="Only the header name, with no colon or value." value=(value); button.remove-header type="button" { "Remove" } @@ -2361,7 +2373,7 @@ fn mcp_servers(servers: &[McpServer], secrets_available: bool) -> Markup { html! { div.card { h2 { "MCP servers" } - p.hint { "Remote MCP servers over HTTPS, offered to agent runs. A project turns one on and picks its stages on its own page. Header values are entered per project." } + p.hint { "Remote MCP servers over HTTPS, and stdio servers the agent starts inside the worker. A project turns one on and picks its stages on its own page. Header values of a remote server are entered per project." } @if !secrets_available { p.hint.bad { "The master key is missing, so header values cannot be saved. The factory still runs, and a project's enabled servers and stages still save." } } @@ -2371,7 +2383,7 @@ fn mcp_servers(servers: &[McpServer], secrets_available: bool) -> Markup { @for server in servers { div.server-row { span.server-name { (server.name) } - span.hint.server-url { (remote_url(server)) } + span.hint.server-url { (server.transport.kind()) ": " (server_summary(server)) } a.link-button href={ "/settings/mcp/" (crate::web::query_escape(&server.name)) } { "Open" } } } @@ -2391,23 +2403,110 @@ fn mcp_servers(servers: &[McpServer], secrets_available: bool) -> Markup { autocapitalize="none" autocomplete="off" spellcheck="false"; p.hint { "1 to 32 characters of a-z, 0-9 and -. It is the key in a run's MCP config and part of the proxy path." } } - div.field { - label for="mcp-new-url" { "URL" } - input #mcp-new-url.wide type="url" name="url" required - placeholder="https://mcp.context7.com/mcp"; - p.hint { "An https URL to the server's streamable-HTTP endpoint." } + fieldset.kind-choice { + legend { "Kind" } + label { input type="radio" name="kind" value="remote" checked; " remote" } + label { input type="radio" name="kind" value="stdio"; " stdio" } + p.hint { "A kind cannot change after the server is added." } + } + div.kind-remote { + div.field { + label for="mcp-new-url" { "URL" } + // No browser validation on the add form's remote fields: a + // hidden field that fails it would block a stdio submit, and + // without JavaScript it cannot be disabled. The server validates. + input #mcp-new-url.wide type="text" inputmode="url" name="url" + placeholder="https://mcp.context7.com/mcp"; + p.hint { "An https URL to the server's streamable-HTTP endpoint." } + } + (header_rows(&[], &html! { + p.hint { "Only the header name, such as " code { "Authorization" } ", with no colon or value. Each project enters its own value on its own page, stored encrypted. A keyless server needs none." } + }, false)) + } + div.kind-stdio { + div.field { + label for="mcp-new-command" { "Command" } + input #mcp-new-command.wide type="text" name="command" + placeholder="npx" maxlength="256" + autocapitalize="none" autocomplete="off" spellcheck="false"; + } + (arg_rows(&[], &html! { (STDIO_HINT) })) } - (header_rows(&[], &html! { - p.hint { "Only the header name, such as " code { "Authorization" } ", with no colon or value. Each project enters its own value on its own page, stored encrypted. A keyless server needs none." } - })) button.primary { "Add server" } } } } -fn remote_url(server: &McpServer) -> &str { - let McpTransport::Remote { url, .. } = &server.transport; - url +/// What the server list shows after the kind: a remote server's URL or a stdio +/// server's command line. +fn server_summary(server: &McpServer) -> String { + match &server.transport { + McpTransport::Remote { url, .. } => url.clone(), + McpTransport::Stdio { command, args } => std::iter::once(command.as_str()) + .chain(args.iter().map(String::as_str)) + .collect::>() + .join(" "), + } +} + +const STDIO_HINT: &str = "The command and base arguments run inside the worker of every project that turns the server on, and each project can append arguments of its own. The agent can read every argument, so no secret belongs here. Each project supplies the command's dependencies through its worker packages. An argument is passed as one value, with no shell splitting, and may not contain ${."; + +/// The argument rows a stdio form shares: one text box per stored argument, +/// each with a Remove button, then three empty boxes for new ones so the form +/// works without JavaScript, then an "Add argument" button and the given +/// `hint`. The arguments post as a repeated `arg` field, and the server drops +/// the empty ones. +fn arg_rows(args: &[String], hint: &Markup) -> Markup { + html! { + div.field { + span.label { "Base arguments" } + div.mcp-args { + @for arg in 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" } + (hint) + } + } +} + +/// A stored argument with a line break, which a one-line input would strip. The +/// input shows it with `\`, line feed and carriage return escaped and posts it +/// as `arg_escaped`, so the value survives a save and an admin can edit it or +/// clear the box to remove it. +fn escaped_arg_row(value: &str) -> Markup { + let shown = value + .replace('\\', "\\\\") + .replace('\r', "\\r") + .replace('\n', "\\n"); + html! { + div.mcp-arg-row { + input.grow type="text" name="arg_escaped" aria-label="Argument with a line break" + autocapitalize="none" autocomplete="off" spellcheck="false" + value=(shown); + button.remove-arg type="button" { "Remove" } + } + } +} + +fn arg_row(value: &str) -> Markup { + html! { + div.mcp-arg-row { + input.grow type="text" name="arg" aria-label="Argument" + autocapitalize="none" autocomplete="off" spellcheck="false" + value=(value); + button.remove-arg type="button" { "Remove" } + } + } } /// One server's edit form on its own page: its URL and header names, a Delete @@ -2415,10 +2514,26 @@ fn remote_url(server: &McpServer) -> &str { /// because it keys the stored secrets and the proxy path. fn mcp_server_form(server: &McpServer, pending: Option<&PendingEdit>) -> Markup { let action = format!("/settings/mcp/{}", server.name); - let McpTransport::Remote { - url: stored_url, - headers: stored_headers, - } = &server.transport; + let (stored_url, stored_headers) = match &server.transport { + McpTransport::Remote { url, headers } => (url, headers), + McpTransport::Stdio { command, args } => { + return html! { + form.card.settings-form method="post" action=(action) { + div.field { + label for={ "mcp-" (server.name) "-command" } { "Command" } + input id={ "mcp-" (server.name) "-command" }.wide type="text" name="command" + required maxlength="256" value=(command) + autocapitalize="none" autocomplete="off" spellcheck="false"; + } + (arg_rows(args, &html! { + p.hint { (STDIO_HINT) } + p.hint { "An edit keeps every project's settings for the server and applies at each job's next run." } + })) + (save_bar("Save")) + } + }; + } + }; let url = pending.map_or(stored_url.as_str(), |pending| pending.url.as_str()); let headers = pending.map_or(stored_headers.as_slice(), |pending| { pending.headers.as_slice() @@ -2457,7 +2572,7 @@ fn mcp_server_form(server: &McpServer, pending: Option<&PendingEdit>) -> Markup (header_rows(headers, &html! { p.hint { "Only the header name, with no colon or value. Each project enters its own value on its own page, stored encrypted." } p.hint { "Removing or renaming a header deletes every project's stored value for it, and changing the URL's host or port deletes all of them. The page asks before it saves such a change. Changing only the path keeps them." } - })) + }, true)) @if pending.is_some() { div.save-bar.dirty { span.save-bar-note { "Unsaved changes." } diff --git a/crates/factory-server/src/proxy.rs b/crates/factory-server/src/proxy.rs index 6d19acb8..cb7b0e05 100644 --- a/crates/factory-server/src/proxy.rs +++ b/crates/factory-server/src/proxy.rs @@ -230,7 +230,10 @@ impl Upstreams for StoreUpstreams { let McpTransport::Remote { url, headers: declared, - } = registered.transport; + } = registered.transport + else { + return None; + }; let mut headers = Vec::new(); for header in &declared { let at = SecretRef { diff --git a/crates/factory-server/src/scheduler.rs b/crates/factory-server/src/scheduler.rs index 68eb6c2d..85a80287 100644 --- a/crates/factory-server/src/scheduler.rs +++ b/crates/factory-server/src/scheduler.rs @@ -1391,6 +1391,10 @@ impl Scheduler { if !(settings.enabled && in_stage) { continue; } + // Runs do not carry stdio servers yet. + if server.as_stdio().is_some() { + continue; + } if self.mcp_secrets_usable(project, &server)? { active.push(server.name); } else { @@ -1410,7 +1414,9 @@ impl Scheduler { /// skips the server, so a broken credential never lands in a worker's /// config. A transient database error propagates and the run waits. fn mcp_secrets_usable(&self, project: &str, server: &McpServer) -> Result { - let McpTransport::Remote { headers, .. } = &server.transport; + let McpTransport::Remote { headers, .. } = &server.transport else { + return Ok(true); + }; for header in headers { let at = SecretRef { project, diff --git a/crates/factory-server/src/store.rs b/crates/factory-server/src/store.rs index bdd1f6ae..1198670c 100644 --- a/crates/factory-server/src/store.rs +++ b/crates/factory-server/src/store.rs @@ -176,7 +176,10 @@ CREATE TABLE IF NOT EXISTS secrets ( CREATE TABLE IF NOT EXISTS mcp_servers ( name TEXT PRIMARY KEY, url TEXT NOT NULL, - headers TEXT NOT NULL + headers TEXT NOT NULL, + kind TEXT NOT NULL DEFAULT 'remote', + command TEXT NOT NULL DEFAULT '', + args TEXT NOT NULL DEFAULT '[]' ); CREATE TABLE IF NOT EXISTS project_mcp ( project TEXT NOT NULL, @@ -599,6 +602,70 @@ impl From for StoreError { } } +/// An `mcp_servers` row's transport columns as stored. +struct StoredTransport { + kind: String, + url: String, + headers: String, + command: String, + args: String, +} + +impl StoredTransport { + /// Validates `transport` and renders it as the columns a row stores. A + /// stdio row keeps an empty URL and header list. + fn validated(transport: &McpTransport) -> Result { + Ok(match transport { + McpTransport::Remote { url, headers } => { + mcp::validate_url(url)?; + let headers = mcp::normalize_headers(headers)?; + StoredTransport { + kind: "remote".to_owned(), + url: url.clone(), + headers: serde_json::to_string(&headers)?, + command: String::new(), + args: "[]".to_owned(), + } + } + McpTransport::Stdio { command, args } => { + let (command, args) = mcp::validate_stdio(command, args)?; + StoredTransport { + kind: "stdio".to_owned(), + url: String::new(), + headers: "[]".to_owned(), + command, + args: serde_json::to_string(&args)?, + } + } + }) + } + + fn into_transport(self) -> Result { + Ok(if self.kind == "stdio" { + McpTransport::Stdio { + command: self.command, + args: serde_json::from_str(&self.args)?, + } + } else { + McpTransport::Remote { + url: self.url, + headers: serde_json::from_str(&self.headers)?, + } + }) + } +} + +/// Reads `kind, url, headers, command, args` from `row`, starting at `from`. +fn mcp_row(row: &rusqlite::Row<'_>, from: usize) -> rusqlite::Result { + Ok(StoredTransport { + kind: row.get(from)?, + url: row.get(from + 1)?, + headers: row.get(from + 2)?, + command: row.get(from + 3)?, + args: row.get(from + 4)?, + }) +} + impl Store { /// Opens or creates the database at `path`. /// @@ -618,11 +685,29 @@ impl Store { Self::init(Connection::open_in_memory()?) } - fn init(conn: Connection) -> Result { - conn.execute_batch(SCHEMA)?; - Self::migrate_project_forge(&conn)?; - Self::migrate_renovate_author(&conn)?; - Self::migrate_upstream_forge(&conn)?; + /// A stdio kind joined the registry after it shipped. Old rows are remote. + fn migrate_mcp_kind(conn: &Connection) -> Result<(), StoreError> { + for (column, definition) in [ + ("kind", "kind TEXT NOT NULL DEFAULT 'remote'"), + ("command", "command TEXT NOT NULL DEFAULT ''"), + ("args", "args TEXT NOT NULL DEFAULT '[]'"), + ] { + let present: i64 = conn.query_row( + "SELECT COUNT(*) FROM pragma_table_info('mcp_servers') WHERE name = ?1", + [column], + |row| row.get(0), + )?; + if present == 0 { + conn.execute( + &format!("ALTER TABLE mcp_servers ADD COLUMN {definition}"), + [], + )?; + } + } + Ok(()) + } + + fn migrate_display_name(conn: &Connection) -> Result<(), StoreError> { let has_display_name: i64 = conn.query_row( "SELECT COUNT(*) FROM pragma_table_info('projects') WHERE name = 'display_name'", [], @@ -631,6 +716,15 @@ impl Store { if has_display_name == 0 { conn.execute("ALTER TABLE projects ADD COLUMN display_name TEXT", [])?; } + Ok(()) + } + + fn init(conn: Connection) -> Result { + conn.execute_batch(SCHEMA)?; + Self::migrate_project_forge(&conn)?; + Self::migrate_renovate_author(&conn)?; + Self::migrate_upstream_forge(&conn)?; + Self::migrate_display_name(&conn)?; // `review` joined the model stages after the table shipped, so add it to // a `project_models` table that predates it. A fresh database already // has the column from SCHEMA, so this skips it. @@ -642,6 +736,7 @@ impl Store { if has_review == 0 { conn.execute("ALTER TABLE project_models ADD COLUMN review TEXT", [])?; } + Self::migrate_mcp_kind(&conn)?; let has_use_my_account: i64 = conn.query_row( "SELECT COUNT(*) FROM pragma_table_info('project_collaborators') WHERE name = 'use_my_account'", [], @@ -4004,25 +4099,20 @@ impl Store { /// /// # Errors /// - /// Fails on a database error or a stored header list that does not parse. + /// Fails on a database error or a stored list that does not parse. pub fn mcp_servers(&self) -> Result, StoreError> { let conn = self.conn(); - let mut stmt = conn.prepare("SELECT name, url, headers FROM mcp_servers ORDER BY name")?; - let rows = stmt.query_map([], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, String>(2)?, - )) - })?; + let mut stmt = conn.prepare( + "SELECT name, kind, url, headers, command, args FROM mcp_servers ORDER BY name", + )?; + let rows = stmt.query_map([], |row| Ok((row.get::<_, String>(0)?, mcp_row(row, 1)?)))?; let mut servers = Vec::new(); for row in rows { - let (name, url, headers) = row?; - servers.push(McpServer::remote( + let (name, stored) = row?; + servers.push(McpServer { name, - url, - serde_json::from_str(&headers)?, - )); + transport: stored.into_transport()?, + }); } Ok(servers) } @@ -4031,44 +4121,63 @@ impl Store { /// /// # Errors /// - /// Fails on a database error or a stored header list that does not parse. + /// Fails on a database error or a stored list that does not parse. pub fn mcp_server(&self, name: &str) -> Result, StoreError> { let row = self .conn() .query_row( - "SELECT url, headers FROM mcp_servers WHERE name = ?1", + "SELECT kind, url, headers, command, args FROM mcp_servers WHERE name = ?1", [name], - |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + |row| mcp_row(row, 0), ) .optional()?; - let Some((url, headers)) = row else { + let Some(stored) = row else { return Ok(None); }; - Ok(Some(McpServer::remote( - name, - url, - serde_json::from_str(&headers)?, - ))) + Ok(Some(McpServer { + name: name.to_owned(), + transport: stored.into_transport()?, + })) } - /// Registers an MCP server. The name, URL and header names are validated, - /// and header names are deduplicated case-insensitively before storage. + /// Registers a remote MCP server. See [`Store::create_mcp_server_with`]. /// /// # Errors /// - /// Returns [`McpError::BadName`], [`McpError::BadUrl`], - /// [`McpError::BadHeader`] or [`McpError::ReservedHeader`] for an invalid - /// field, and [`McpError::DuplicateName`] when `name` is taken. Nothing is - /// written when it fails. + /// As [`Store::create_mcp_server_with`]. pub fn create_mcp_server( &self, name: &str, url: &str, headers: &[String], + ) -> Result<(), McpError> { + self.create_mcp_server_with( + name, + &McpTransport::Remote { + url: url.to_owned(), + headers: headers.to_vec(), + }, + ) + } + + /// Registers an MCP server. The name and the transport's fields are + /// validated; header names are deduplicated case-insensitively and a stdio + /// command is trimmed and its empty arguments dropped before storage. + /// + /// # Errors + /// + /// Returns [`McpError::BadName`], [`McpError::BadUrl`], + /// [`McpError::BadHeader`], [`McpError::ReservedHeader`], + /// [`McpError::BadCommand`] or [`McpError::BadArgs`] for an invalid field, + /// and [`McpError::DuplicateName`] when `name` is taken, by either kind. + /// Nothing is written when it fails. + pub fn create_mcp_server_with( + &self, + name: &str, + transport: &McpTransport, ) -> Result<(), McpError> { mcp::validate_name(name)?; - mcp::validate_url(url)?; - let headers = mcp::normalize_headers(headers)?; + let stored = StoredTransport::validated(transport)?; let mut conn = self.conn(); let tx = conn.transaction()?; let taken = tx @@ -4081,71 +4190,115 @@ impl Store { return Err(McpError::DuplicateName(name.to_owned())); } tx.execute( - "INSERT INTO mcp_servers (name, url, headers) VALUES (?1, ?2, ?3)", - params![name, url, serde_json::to_string(&headers)?], + "INSERT INTO mcp_servers (name, kind, url, headers, command, args) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + name, + stored.kind, + stored.url, + stored.headers, + stored.command, + stored.args + ], )?; tx.commit()?; Ok(()) } - /// Edits the URL and header names of the server `name`. The name itself does - /// not change, because it keys the stored secrets and the proxy path. - /// - /// When the new URL's origin (scheme, host or port) differs from the old - /// one, every project's stored secret value for this server is deleted, so a - /// redirected server cannot collect another project's keys, and every stored - /// tool is marked as not offered until the next refresh. Each tool keeps its - /// on or off state. Otherwise, each - /// header name no longer declared has its stored values deleted. Both happen - /// in the same transaction as the update. + /// Edits a remote server. See [`Store::edit_mcp_server_with`]. /// /// # Errors /// - /// Returns [`McpError::BadUrl`], [`McpError::BadHeader`] or - /// [`McpError::ReservedHeader`] for an invalid field, and - /// [`McpError::NotFound`] when no server is registered under `name`. Nothing - /// is written when it fails. + /// As [`Store::edit_mcp_server_with`]. pub fn edit_mcp_server( &self, name: &str, url: &str, headers: &[String], ) -> Result<(), McpError> { - mcp::validate_url(url)?; - let headers = mcp::normalize_headers(headers)?; + self.edit_mcp_server_with( + name, + &McpTransport::Remote { + url: url.to_owned(), + headers: headers.to_vec(), + }, + ) + } + + /// Edits the transport of the server `name`. The name itself does not + /// change, because it keys the stored secrets and the proxy path, and the + /// kind does not change either. + /// + /// For a remote server: when the new URL's origin (scheme, host or port) + /// differs from the old one, every project's stored secret value for this + /// server is deleted, so a redirected server cannot collect another + /// project's keys, and every stored tool is marked as not offered until the + /// next refresh. Each tool keeps its on or off state. Otherwise, each + /// header name no longer declared has its stored values deleted. Both happen + /// in the same transaction as the update. + /// + /// For a stdio server the command and base arguments are replaced and + /// every project's settings for it stay, because it has no stored values. + /// + /// # Errors + /// + /// Returns [`McpError::BadUrl`], [`McpError::BadHeader`], + /// [`McpError::ReservedHeader`], [`McpError::BadCommand`] or + /// [`McpError::BadArgs`] for an invalid field, [`McpError::KindChange`] when + /// `transport` is not the server's kind, and [`McpError::NotFound`] when no + /// server is registered under `name`. Nothing is written when it fails. + pub fn edit_mcp_server_with( + &self, + name: &str, + transport: &McpTransport, + ) -> Result<(), McpError> { + let stored = StoredTransport::validated(transport)?; let mut conn = self.conn(); let tx = conn.transaction()?; let existing = tx .query_row( - "SELECT url, headers FROM mcp_servers WHERE name = ?1", + "SELECT kind, url, headers, command, args FROM mcp_servers WHERE name = ?1", [name], - |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + |row| mcp_row(row, 0), ) .optional()?; - let Some((old_url, old_headers)) = existing else { + let Some(existing) = existing else { return Err(McpError::NotFound(name.to_owned())); }; - if mcp::same_origin(&old_url, url) { - let old_headers: Vec = serde_json::from_str(&old_headers)?; - for removed in old_headers - .iter() - .filter(|old| !headers.iter().any(|kept| kept.eq_ignore_ascii_case(old))) - { + if existing.kind != stored.kind { + return Err(McpError::KindChange(name.to_owned())); + } + if let McpTransport::Remote { url, .. } = transport { + let headers: Vec = serde_json::from_str(&stored.headers)?; + if mcp::same_origin(&existing.url, url) { + let old_headers: Vec = serde_json::from_str(&existing.headers)?; + for removed in old_headers + .iter() + .filter(|old| !headers.iter().any(|kept| kept.eq_ignore_ascii_case(old))) + { + tx.execute( + "DELETE FROM secrets WHERE server = ?1 AND header = ?2", + params![name, removed], + )?; + } + } else { + tx.execute("DELETE FROM secrets WHERE server = ?1", [name])?; tx.execute( - "DELETE FROM secrets WHERE server = ?1 AND header = ?2", - params![name, removed], + "UPDATE project_mcp_tools SET offered = 0 WHERE server = ?1", + [name], )?; } - } else { - tx.execute("DELETE FROM secrets WHERE server = ?1", [name])?; - tx.execute( - "UPDATE project_mcp_tools SET offered = 0 WHERE server = ?1", - [name], - )?; } tx.execute( - "UPDATE mcp_servers SET url = ?1, headers = ?2 WHERE name = ?3", - params![url, serde_json::to_string(&headers)?, name], + "UPDATE mcp_servers SET url = ?1, headers = ?2, command = ?3, args = ?4 + WHERE name = ?5", + params![ + stored.url, + stored.headers, + stored.command, + stored.args, + name + ], )?; tx.commit()?; Ok(()) @@ -4174,7 +4327,8 @@ impl Store { /// # Errors /// /// Fails as [`Store::edit_mcp_server`] would, on an invalid URL or header - /// name, an unknown server or a database error. + /// name, an unknown server or a database error. A stdio server gives an + /// empty list. pub fn mcp_edit_deletes( &self, name: &str, @@ -4186,8 +4340,11 @@ impl Store { let Some(server) = self.mcp_server(name)? else { return Err(McpError::NotFound(name.to_owned())); }; + // A stdio server has no stored values, so an edit deletes none. + let Some((current, _)) = server.as_remote() else { + return Ok(Vec::new()); + }; let stored = self.mcp_secrets(name)?; - let McpTransport::Remote { url: current, .. } = &server.transport; if !mcp::same_origin(current, url) { return Ok(stored); } diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 106e3dc8..976bece7 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -2028,6 +2028,8 @@ 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 @@ -2253,6 +2255,9 @@ 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; @@ -3298,8 +3303,8 @@ fn server_settings( server: McpServer, ) -> Result { let saved = state.store.project_mcp(project, &server.name)?; - let McpTransport::Remote { headers, .. } = &server.transport; - let headers = headers + let declared = server.as_remote().map_or(&[][..], |(_, headers)| headers); + let headers = declared .iter() .map(|header: &String| { let at = SecretRef { @@ -3334,6 +3339,7 @@ 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:?}"))) } @@ -3393,10 +3399,9 @@ async fn save_project_mcp( form.get(&format!("{base}.header.{header}")) .filter(|value| !value.is_empty()) }; - let McpTransport::Remote { - headers: registered_headers, - .. - } = ®istered.transport; + let registered_headers = registered + .as_remote() + .map_or(&[][..], |(_, headers)| headers); if !state.secrets.available() && registered_headers .iter() @@ -3441,34 +3446,82 @@ async fn save_project_mcp( project_mcp_page(&state, &headers, &project, &server, Some("Saved.")) } -/// An MCP server form: its `url` and one `header` field per header-name row. The -/// rows post as a repeated `header` field, so the form parses as a list of pairs -/// rather than a struct. The Add form also posts a `name`; the edit route takes -/// the name from its path and ignores any posted one. +/// An MCP server form: a `kind`, the remote fields `url` and one `header` field +/// per header-name row, and the stdio fields `command` and one `arg` field per +/// argument row. Rows post as repeated fields, so the form parses as a list of +/// pairs rather than a struct. The Add form also posts a `name`; the edit route +/// takes the name from its path and ignores any posted one. struct McpServerForm { name: String, + /// Whether the posted kind is `stdio`, when one was posted. The edit route + /// only checks it against the stored kind, because the kind is fixed. + stdio: Option, url: String, headers: Vec, + command: String, + args: Vec, /// Set when the operator confirmed an edit that deletes stored values. confirm: bool, } +/// Reads an argument the edit form escaped so that a one-line input can carry +/// it: `\\` is a backslash, `\n` a line feed and `\r` a carriage return. +fn unescape_arg(value: &str) -> Result { + let mut out = String::with_capacity(value.len()); + let mut chars = value.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('\\') => out.push('\\'), + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + _ => { + return Err(McpError::BadArgs( + "an escaped argument has a backslash that is not \\\\, \\n or \\r".to_owned(), + )); + } + } + } + Ok(out) +} + impl McpServerForm { - /// Reads `name`, `url` and the repeated `header` field out of the posted - /// pairs. Each header name is trimmed and an empty one, from a blank row, is - /// dropped. The store validates and deduplicates the names. - fn from_pairs(pairs: Vec<(String, String)>) -> Self { + /// Reads the posted pairs. Each header name is trimmed and an empty one, + /// from a blank row, is dropped. An argument is kept as typed, because a + /// space in it is part of it; the store drops an empty one. The store + /// validates both lists. + fn from_pairs(pairs: Vec<(String, String)>) -> Result { let mut form = McpServerForm { name: String::new(), + stdio: None, url: String::new(), headers: Vec::new(), + command: String::new(), + args: Vec::new(), confirm: false, }; for (key, value) in pairs { match key.as_str() { "name" => form.name = value, + "kind" => { + form.stdio = Some(match value.as_str() { + "stdio" => true, + "remote" => false, + _ => { + return Err(McpError::BadKind(format!( + "the kind {value:?} is not remote or stdio" + ))); + } + }); + } "url" => form.url = value, + "command" => form.command = value, "confirm" => form.confirm = true, + "arg" => form.args.push(value), + "arg_escaped" => form.args.push(unescape_arg(&value)?), "header" => { let name = value.trim(); if !name.is_empty() { @@ -3478,7 +3531,22 @@ impl McpServerForm { _ => {} } } - form + Ok(form) + } + + /// The transport the posted fields describe, ignoring the other kind's. + fn transport(&self, stdio: bool) -> McpTransport { + if stdio { + McpTransport::Stdio { + command: self.command.clone(), + args: self.args.clone(), + } + } else { + McpTransport::Remote { + url: self.url.trim().to_owned(), + headers: self.headers.clone(), + } + } } } @@ -3487,10 +3555,11 @@ async fn add_mcp_server( headers: HeaderMap, Form(pairs): Form>, ) -> Result { - let form = McpServerForm::from_pairs(pairs); + let form = McpServerForm::from_pairs(pairs)?; + let transport = form.transport(form.stdio == Some(true)); state .store - .create_mcp_server(form.name.trim(), form.url.trim(), &form.headers)?; + .create_mcp_server_with(form.name.trim(), &transport)?; mcp_server_page(&state, &headers, form.name.trim(), Some("Added.")) } @@ -3500,29 +3569,43 @@ async fn edit_mcp_server( Path(name): Path, Form(pairs): Form>, ) -> Result { - let form = McpServerForm::from_pairs(pairs); - let url = form.url.trim(); + let form = McpServerForm::from_pairs(pairs)?; + let Some(registered) = state.store.mcp_server(&name)? else { + return Err(McpError::NotFound(name).into()); + }; + let stdio = registered.as_stdio().is_some(); + if form.stdio.is_some_and(|posted| posted != stdio) { + return Err(McpError::KindChange(name).into()); + } + let transport = form.transport(stdio); // An edit that deletes stored values waits for the operator to confirm it. - let deletes = state.store.mcp_edit_deletes(&name, url, &form.headers)?; - if !deletes.is_empty() && !form.confirm { - let total = deletes.len(); - let visible = project_labels(&state, &user(&headers))?; - let shown = deletes - .into_iter() - .filter_map(|(project, header)| { - let label = visible.iter().find(|label| label.id == project)?; - Some((label.clone(), header)) - }) - .collect(); - let pending = pages::PendingEdit { - url: url.to_owned(), - headers: form.headers, - deletes: shown, - total, - }; - return mcp_server_page_with(&state, &headers, &name, None, Some(&pending), None); + // A stdio server has none, so it saves at once. + if let McpTransport::Remote { + url, + headers: names, + } = &transport + { + let deletes = state.store.mcp_edit_deletes(&name, url, names)?; + if !deletes.is_empty() && !form.confirm { + let total = deletes.len(); + let visible = project_labels(&state, &user(&headers))?; + let shown = deletes + .into_iter() + .filter_map(|(project, header)| { + let label = visible.iter().find(|label| label.id == project)?; + Some((label.clone(), header)) + }) + .collect(); + let pending = pages::PendingEdit { + url: url.clone(), + headers: names.clone(), + deletes: shown, + total, + }; + return mcp_server_page_with(&state, &headers, &name, None, Some(&pending), None); + } } - state.store.edit_mcp_server(&name, url, &form.headers)?; + state.store.edit_mcp_server_with(&name, &transport)?; mcp_server_page(&state, &headers, &name, Some("Saved.")) } @@ -3567,6 +3650,12 @@ async fn check_mcp_server( "no MCP server named {server:?}" ))); }; + // A stdio server runs inside the worker, so the factory cannot reach it. + if registered.as_stdio().is_some() { + return Err(AppError::BadRequest(format!( + "the server {server:?} runs inside the worker, so its connection cannot be checked" + ))); + } // Resolve the saved URL and values the way the proxy does, so the check and // a run send the same headers. `resolve` returns `None` only for a server // that is not registered, which the lookup above has ruled out. @@ -3577,10 +3666,9 @@ async fn check_mcp_server( // A declared header with no resolved value has none stored, or one that // would not decrypt. The result names these, and the check runs without // them. - let McpTransport::Remote { - headers: registered_headers, - .. - } = ®istered.transport; + let registered_headers = registered + .as_remote() + .map_or(&[][..], |(_, headers)| headers); let missing: Vec = registered_headers .iter() .filter(|name| !headers.iter().any(|(have, _)| have == *name)) diff --git a/crates/factory-server/static/mcp-header-rows.js b/crates/factory-server/static/mcp-header-rows.js deleted file mode 100644 index 572fc006..00000000 --- a/crates/factory-server/static/mcp-header-rows.js +++ /dev/null @@ -1,25 +0,0 @@ -// The "Add header" and "Remove" buttons on the MCP server forms. Each header -// name sits in its own text box inside a `.mcp-headers` list. "Add header" -// clones the list's last row as an empty box; "Remove" drops its row. The forms -// still work without this script: you add one name per save and remove a name by -// clearing its box. Delegated from the document, so it covers every server form -// on the settings page, including rows added after load. -(function () { - document.addEventListener("click", function (event) { - var button = event.target; - if (button.classList.contains("add-header")) { - var field = button.closest(".field"); - var list = field && field.querySelector(".mcp-headers"); - var rows = list && list.querySelectorAll(".mcp-header-row"); - if (!rows || !rows.length) return; - var row = rows[rows.length - 1].cloneNode(true); - var input = row.querySelector("input"); - input.value = ""; - list.appendChild(row); - input.focus(); - } else if (button.classList.contains("remove-header")) { - var row = button.closest(".mcp-header-row"); - if (row) row.remove(); - } - }); -})(); diff --git a/crates/factory-server/static/mcp-rows.js b/crates/factory-server/static/mcp-rows.js new file mode 100644 index 00000000..cc6a19a6 --- /dev/null +++ b/crates/factory-server/static/mcp-rows.js @@ -0,0 +1,23 @@ +(function () { + var kinds = [ + { add: "add-header", remove: "remove-header", list: ".mcp-headers", row: ".mcp-header-row" }, + { add: "add-arg", remove: "remove-arg", list: ".mcp-args", row: ".mcp-arg-row" }, + ]; + document.addEventListener("click", function (event) { + var button = event.target; + kinds.forEach(function (kind) { + if (button.classList.contains(kind.add)) { + var field = button.closest(".field"); + var list = field && field.querySelector(kind.list); + var template = field && field.querySelector("template"); + if (!list || !template) return; + var row = template.content.firstElementChild.cloneNode(true); + list.appendChild(row); + row.querySelector("input").focus(); + } else if (button.classList.contains(kind.remove)) { + var gone = button.closest(kind.row); + if (gone) gone.remove(); + } + }); + }); +})(); diff --git a/crates/factory-server/static/settings-form.js b/crates/factory-server/static/settings-form.js index d40a52a5..c7ca9631 100644 --- a/crates/factory-server/static/settings-form.js +++ b/crates/factory-server/static/settings-form.js @@ -25,13 +25,13 @@ document.addEventListener("input", mark); document.addEventListener("change", mark); - // Adding or removing a header row changes the form without an input event. - // This listens in the capture phase, before the header-row script removes - // the clicked row from its form. + // Adding or removing a header or argument row changes the form without an + // input event. This listens in the capture phase, before the row script + // removes the clicked row from its form. document.addEventListener( "click", function (event) { - if (event.target.matches(".add-header, .remove-header")) mark(event); + if (event.target.matches(".add-header, .remove-header, .add-arg, .remove-arg")) mark(event); }, true, ); diff --git a/crates/factory-server/static/style.css b/crates/factory-server/static/style.css index 01fa7810..45dc0b30 100644 --- a/crates/factory-server/static/style.css +++ b/crates/factory-server/static/style.css @@ -418,9 +418,14 @@ select:focus, textarea:focus, button:focus-visible { outline: var(--focus-ring); .field { margin-bottom: var(--space-14); } .field > .label { display: block; font-weight: var(--weight-semibold); margin: 0 0 var(--space-6); } -.mcp-header-row { display: flex; gap: var(--space-8); align-items: center; margin-bottom: var(--space-8); } -.mcp-header-row > .grow { flex: 1 1 auto; } -.mcp-headers + .add-header { margin-bottom: 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-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); } +/* Without JavaScript both groups exist; the checked kind decides which shows. */ +form:has(input[name=kind][value=stdio]:checked) .kind-remote, +form:not(:has(input[name=kind][value=stdio]:checked)) .kind-stdio { display: none; } .codex-prices { display: flex; flex-direction: column; gap: var(--space-12); margin-bottom: var(--space-16); } .price-row, .price-add { display: flex; flex-wrap: wrap; gap: var(--space-12); align-items: flex-end; } diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index 24cacbfb..0fb9c5be 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -10277,6 +10277,180 @@ async fn an_mcp_server_is_added_edited_and_deleted_through_the_settings_page() { assert!(dashboard.store.mcp_server("context7").unwrap().is_none()); } +#[tokio::test] +async fn a_stdio_mcp_server_is_added_edited_and_deleted_through_the_settings_page() { + let dashboard = dashboard(); + let added = dashboard + .post( + "/settings/mcp", + "name=playwright&kind=stdio&command=npx&arg=-y&arg=&arg=%40playwright%2Fmcp%400.0.83\ + &url=https%3A%2F%2Fignored.test%2Fmcp&header=Authorization", + ) + .await; + assert_eq!(added.status, StatusCode::OK); + assert!(added.body.contains("stdio")); + assert!(added.body.contains("@playwright/mcp@0.0.83")); + let server = dashboard.store.mcp_server("playwright").unwrap().unwrap(); + assert_eq!( + server.as_stdio().unwrap(), + ( + "npx", + &["-y".to_owned(), "@playwright/mcp@0.0.83".to_owned()][..] + ), + ); + + let list = dashboard.get("/settings/mcp").await; + assert!(list.body.contains("stdio: npx -y @playwright/mcp@0.0.83")); + + let edited = dashboard + .post( + "/settings/mcp/playwright", + "command=uvx&arg=pkg&arg=--flag%3Da+b", + ) + .await; + assert_eq!(edited.status, StatusCode::OK); + let server = dashboard.store.mcp_server("playwright").unwrap().unwrap(); + assert_eq!( + server.as_stdio().unwrap(), + ("uvx", &["pkg".to_owned(), "--flag=a b".to_owned()][..]), + ); + + let deleted = dashboard + .post("/settings/mcp/playwright/delete", "confirm_name=playwright") + .await; + assert_eq!(deleted.status, StatusCode::OK); + 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(); + dashboard + .store + .create_mcp_server_with( + "playwright", + &factory_server::McpTransport::Stdio { + command: "npx".to_owned(), + args: Vec::new(), + }, + ) + .unwrap(); + let check = dashboard + .post("/settings/projects/maestro/mcp/playwright/check", "") + .await; + assert_eq!(check.status, StatusCode::BAD_REQUEST); + assert_eq!(dashboard.checker.calls(), 0); + let project = dashboard.get("/settings/projects/maestro").await; + assert!(!project.body.contains("playwright")); +} + +#[tokio::test] +async fn an_invalid_stdio_mcp_server_is_a_bad_request() { + let dashboard = dashboard(); + for form in [ + "name=p&kind=stdio&command=", + "name=p&kind=stdio&command=a%0Ab", + "name=p&kind=stdio&command=%0Anpx", + "name=p&kind=stdio&command=npx%0D", + "name=p&kind=stido&command=npx", + "name=p&kind=stido&url=https%3A%2F%2Fmcp.context7.com%2Fmcp", + "name=p&kind=stdio&command=npx&arg=%24%7BHOME%7D", + ] { + let reply = dashboard.post("/settings/mcp", form).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST, "{form}"); + } + let many = "&arg=a".repeat(65); + let reply = dashboard + .post( + "/settings/mcp", + &format!("name=p&kind=stdio&command=npx{many}"), + ) + .await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(dashboard.store.mcp_servers().unwrap(), Vec::new()); + + // An edit cannot change the kind: a remote server ignores stdio fields. + dashboard + .store + .create_mcp_server("context7", "https://mcp.context7.com/mcp", &[]) + .unwrap(); + let reply = dashboard + .post( + "/settings/mcp/context7", + "kind=stdio&url=https%3A%2F%2Fmcp.context7.com%2Fmcp&command=npx", + ) + .await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + let kept = dashboard.store.mcp_server("context7").unwrap().unwrap(); + assert_eq!(kept.as_remote().unwrap().0, "https://mcp.context7.com/mcp"); + // A stdio server refuses an explicit remote kind too. + dashboard + .store + .create_mcp_server_with( + "pw", + &factory_server::McpTransport::Stdio { + command: "npx".to_owned(), + args: Vec::new(), + }, + ) + .unwrap(); + let reply = dashboard + .post("/settings/mcp/pw", "kind=remote&command=uvx") + .await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!( + dashboard + .store + .mcp_server("pw") + .unwrap() + .unwrap() + .as_stdio() + .unwrap() + .0, + "npx" + ); +} + +#[tokio::test] +async fn a_stdio_edit_keeps_arguments_with_line_breaks() { + let dashboard = dashboard(); + let reply = dashboard + .post( + "/settings/mcp", + "name=pw&kind=stdio&command=npx&arg=a%0Ab&arg=c%0Dd&arg=--headless", + ) + .await; + assert_eq!(reply.status, StatusCode::OK); + let stored = |dashboard: &Dashboard| { + let server = dashboard.store.mcp_server("pw").unwrap().unwrap(); + let (command, args) = server.as_stdio().unwrap(); + (command.to_owned(), args.to_vec()) + }; + let args = vec![ + "a\nb".to_owned(), + "c\rd".to_owned(), + "--headless".to_owned(), + ]; + assert_eq!(stored(&dashboard), ("npx".to_owned(), args.clone())); + let page = dashboard.get("/settings/mcp/pw").await; + assert_eq!(page.body.matches(r#"name="arg_escaped""#).count(), 2); + assert!(page.body.contains(r#"value="a\nb""#)); + assert!(page.body.contains(r#"value="c\rd""#)); + let reply = dashboard + .post( + "/settings/mcp/pw", + "command=uvx&arg_escaped=a%5Cnb&arg_escaped=c%5Crd&arg=--headless", + ) + .await; + assert_eq!(reply.status, StatusCode::OK); + assert_eq!(stored(&dashboard), ("uvx".to_owned(), args)); + let reply = dashboard + .post("/settings/mcp/pw", "command=uvx&arg_escaped=a%5Cqb") + .await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(stored(&dashboard).0, "uvx"); +} + #[tokio::test] async fn an_invalid_mcp_server_is_a_bad_request() { let dashboard = dashboard(); @@ -10303,13 +10477,17 @@ async fn an_invalid_mcp_server_is_a_bad_request() { #[tokio::test] async fn the_add_server_form_has_header_name_rows_not_a_textarea() { let dashboard = dashboard(); + dashboard + .store + .create_mcp_server("context7", "https://mcp.context7.com/mcp", &[]) + .unwrap(); let page = dashboard.settings_pages().await; // The header names live in text boxes posting a repeated `header` field, // with an "Add header" button, and no textarea or `headers` field remains. assert!(page.contains(r#"name="header""#)); assert!(page.contains("Add header")); - // The header-name pattern escapes `|` and the trailing `-`, as the `v` flag - // a browser compiles it with requires. + // The edit form's header-name pattern escapes `|` and the trailing `-`, as + // the `v` flag a browser compiles it with requires. assert!(page.contains(r"\|~\-]+")); assert!(!page.contains(r#"name="headers""#)); assert!(!page.contains("