From 1552bb71bb794b37dbbd64a3a7eca24e15ab6379 Mon Sep 17 00:00:00 2001 From: Bastien Gallay Date: Sun, 22 Nov 2026 22:28:45 +0100 Subject: [PATCH 1/3] refactor: write mcp config before PTY spawn and dispatch cli::Command with match --- crates/app/src/main.rs | 9 ++++++--- crates/pty/src/manager.rs | 31 +++++++++++++++++++------------ 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index f798884..11c9bbe 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -49,9 +49,12 @@ fn main() -> iced::Result { // that would disturb it: the single-instance lock below exits(2) on a second // process, which is the wrong answer to `termherd mcp-config`. Nor does it // open the log file, which could rotate the running instance's log. - if cli::parse(std::env::args()) == cli::Command::McpConfig { - tracing_init::init_tracing(None); - return report_mcp_config(data_dir.as_ref()); + match cli::parse(std::env::args()) { + cli::Command::McpConfig => { + tracing_init::init_tracing(None); + return report_mcp_config(data_dir.as_ref()); + } + cli::Command::Gui => {} } tracing_init::init_tracing(log_file::path(data_dir.as_ref()).as_deref()); diff --git a/crates/pty/src/manager.rs b/crates/pty/src/manager.rs index 247d9e2..ffdead6 100644 --- a/crates/pty/src/manager.rs +++ b/crates/pty/src/manager.rs @@ -175,10 +175,22 @@ impl PtyHost for PtyManager { }; apply_integration(&self.private, spec.session, &program, &mut cmd); - let child = pair - .slave - .spawn_command(cmd) - .map_err(|e| PtyError::Spawn(e.to_string()))?; + // Write the per-session `mcpServers` config before spawning the shell, + // so both argv-based launches (`--mcp-config`) and env-based proxies + // can reference it. If spawning fails, discard every private file we + // just created so bearer tokens and startup dirs do not leak. + let mcp_config_path = spec + .mcp + .as_ref() + .and_then(|config| write_mcp_config(&self.private, spec.session, config)); + + let child = match pair.slave.spawn_command(cmd) { + Ok(child) => child, + Err(error) => { + discard_private_files(&self.private, spec.session); + return Err(PtyError::Spawn(error.to_string())); + } + }; // The slave fd must close in this process so the reader sees EOF when // the child exits. drop(pair.slave); @@ -196,14 +208,9 @@ impl PtyHost for PtyManager { let shell_pid = child.process_id(); let master: SharedMaster = Arc::new(Mutex::new(pair.master)); - // Start Claude by typing into the fresh shell (see `launch_command`). - // Shells buffer stdin, so writing immediately is safe even before the - // prompt appears. A Claude launch with an mcp endpoint first writes the - // `mcpServers` config file `--mcp-config` points at. - let mcp_config_path = spec - .mcp - .as_ref() - .and_then(|config| write_mcp_config(&self.private, spec.session, config)); + // Start the agent CLI by typing into the fresh shell (see + // `launch_command`). Shells buffer stdin, so writing immediately is + // safe even before the prompt appears. // A Claude launch also carries the settings overlay that keeps its OSC // title — termherd's only status channel for it — switched on. let settings_path = (spec.launch.provider() == Some(termherd_core::Provider::Claude)) From 765ad9667fff196ee7f317c9e14ee0cb085afc93 Mon Sep 17 00:00:00 2001 From: Bastien Gallay Date: Sun, 22 Nov 2026 22:35:02 +0100 Subject: [PATCH 2/3] feat(mcp): add termherd mcp-proxy and export TERMHERD_MCP_CONFIG for Antigravity sessions --- CHANGELOG.md | 10 + crates/app/src/cli.rs | 7 + crates/app/src/main.rs | 11 + crates/app/src/mcp_proxy.rs | 600 +++++++++++++++++++++++++++++++++++ crates/app/src/paths.rs | 8 + crates/app/src/shell.rs | 22 ++ crates/core/src/locations.rs | 22 ++ crates/core/src/provider.rs | 5 +- crates/pty/src/launch.rs | 65 ++++ crates/pty/src/manager.rs | 7 +- docs/src/mcp/live-bridge.md | 19 ++ 11 files changed, 772 insertions(+), 4 deletions(-) create mode 100644 crates/app/src/mcp_proxy.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b0da7a3..44b4731 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added (`termherd mcp-proxy` for Antigravity and non-`--mcp-config` CLIs) + +- Added the `termherd mcp-proxy` subcommand, a stdio-to-HTTP bridge that reads + `TERMHERD_MCP_CONFIG` (exported into every agent session's PTY environment, + pointing at the per-session `0600` config file) and forwards JSON-RPC to the + parent instance's live bridge. Registering `termherd mcp-proxy` once in `agy` + gives Antigravity sessions launched from TermHerd all live workspace tools; + outside TermHerd, it serves `settings.json` tools with explicit `initialize` + instructions explaining why the live tools are unavailable. + ### Changed (larger, steadier text sizes) - The interface's text takes four sizes instead of eight: 11 for secondary diff --git a/crates/app/src/cli.rs b/crates/app/src/cli.rs index 3212e02..db6fb97 100644 --- a/crates/app/src/cli.rs +++ b/crates/app/src/cli.rs @@ -22,11 +22,16 @@ pub(crate) enum Command { Gui, /// Print the `mcpServers` snippet for the running instance, then exit. McpConfig, + /// Run a stdio-to-HTTP MCP proxy to the parent session's live bridge. + McpProxy, } /// The subcommand that asks the running instance for its bridge config. const MCP_CONFIG: &str = "mcp-config"; +/// The subcommand that proxies stdio MCP traffic to the session's live bridge. +const MCP_PROXY: &str = "mcp-proxy"; + /// Read the command out of `args`, which is the raw `std::env::args` including /// the program name. /// @@ -37,6 +42,7 @@ const MCP_CONFIG: &str = "mcp-config"; pub(crate) fn parse>(args: I) -> Command { match args.into_iter().nth(1).as_deref() { Some(MCP_CONFIG) => Command::McpConfig, + Some(MCP_PROXY) => Command::McpProxy, _ => Command::Gui, } } @@ -97,6 +103,7 @@ mod tests { #[test] fn the_subcommand_is_recognised_and_nothing_else_is() { assert_eq!(parse(argv(&[MCP_CONFIG])), Command::McpConfig); + assert_eq!(parse(argv(&[MCP_PROXY])), Command::McpProxy); assert_eq!(parse(argv(&[])), Command::Gui); } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 11c9bbe..aa78f62 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -20,6 +20,7 @@ mod log_file; #[cfg(target_os = "macos")] mod macos; mod mcp; +mod mcp_proxy; mod metadata_store; mod paths; mod providers; @@ -54,6 +55,16 @@ fn main() -> iced::Result { tracing_init::init_tracing(None); return report_mcp_config(data_dir.as_ref()); } + cli::Command::McpProxy => { + let config_path = paths::mcp_config_path(); + let settings_file = data_dir.as_ref().map(settings::path); + if let Err(err) = mcp_proxy::run(config_path.as_deref(), settings_file.as_deref()) { + use std::io::Write; + let _ = writeln!(std::io::stderr(), "termherd mcp-proxy: {err}"); + std::process::exit(1); + } + return Ok(()); + } cli::Command::Gui => {} } diff --git a/crates/app/src/mcp_proxy.rs b/crates/app/src/mcp_proxy.rs new file mode 100644 index 0000000..e186272 --- /dev/null +++ b/crates/app/src/mcp_proxy.rs @@ -0,0 +1,600 @@ +//! `termherd mcp-proxy` — stdio-to-HTTP bridge for agent CLIs without a +//! `--mcp-config` flag (such as Antigravity). +//! +//! When TermHerd spawns an agent session it writes the session's private `0600` +//! `mcpServers` JSON file and exports its path in `TERMHERD_MCP_CONFIG`. A CLI +//! registered once with `termherd mcp-proxy` inherits that variable, so every +//! session launched from TermHerd gets all live workspace tools over a +//! per-session revocable bearer token. +//! +//! No silent fallback: +//! - When `TERMHERD_MCP_CONFIG` is **set** but unreadable, malformed, or the +//! live bridge refuses/drops the request, the proxy reports an error (exit 1 +//! at startup, or a JSON-RPC error per request) and never falls back to +//! `settings.json`. +//! - When `TERMHERD_MCP_CONFIG` is **absent** (launched outside TermHerd, or a +//! host CLI that does not propagate the variable), the proxy logs why on +//! stderr and serves the `settings.json` tools with explicit `initialize` +//! `instructions` stating why the live tools are unavailable. + +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream}; +use std::path::Path; +use std::time::Duration; + +use serde_json::{Value, json}; +use thiserror::Error; + +/// Timeout for establishing the loopback TCP connection. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); +/// Timeout for writing a request to the loopback bridge. +const WRITE_TIMEOUT: Duration = Duration::from_secs(5); +/// Timeout for reading a reply from the loopback bridge. Must exceed the live +/// bridge's longest bounded tool call (`wait_for_status` caps at 60 s). +const READ_TIMEOUT: Duration = Duration::from_secs(120); +/// Upper bound on HTTP response headers read from the loopback bridge. +const MAX_HEADER_BYTES: usize = 64 * 1024; +/// Upper bound on an HTTP response body (screenshots are base64 PNGs). +const MAX_BODY_BYTES: usize = 16 * 1024 * 1024; + +/// Server instructions emitted in `initialize` when `TERMHERD_MCP_CONFIG` is +/// absent, so neither the user nor the model mistakes settings-only mode for a +/// working live bridge. +pub(crate) const MISSING_ENV_INSTRUCTIONS: &str = "TermHerd live bridge is not active because TERMHERD_MCP_CONFIG is not set in this \ + process's environment (launched outside TermHerd, or the host CLI did not propagate \ + the variable). Only settings.json tools (list_options, set_option) are available."; + +/// Parsed loopback target extracted from a `termherd-mcp-.json` file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct BridgeTarget { + pub(crate) addr: SocketAddr, + pub(crate) host_header: String, + pub(crate) path: String, + pub(crate) token: String, +} + +#[derive(Debug, Error)] +pub(crate) enum ProxyConfigError { + #[error("could not read {path}: {source}")] + Io { + path: String, + #[source] + source: io::Error, + }, + #[error("config is not valid JSON: {0}")] + InvalidJson(#[from] serde_json::Error), + #[error("config is missing mcpServers.termherd")] + MissingServer, + #[error("bridge URL is not a loopback HTTP endpoint: {0}")] + InvalidUrl(String), + #[error("config is missing a Bearer Authorization header")] + MissingToken, +} + +#[derive(Debug, Error)] +pub(crate) enum TransportError { + #[error("could not connect to live bridge at {addr}: {source}")] + Connect { + addr: SocketAddr, + #[source] + source: io::Error, + }, + #[error("I/O error talking to live bridge: {0}")] + Io(#[from] io::Error), + #[error("malformed HTTP response from live bridge: {0}")] + MalformedHttp(String), + #[error("live bridge refused the session token (HTTP {0})")] + Unauthorized(u16), + #[error("live bridge returned HTTP {status}: {body}")] + HttpStatus { status: u16, body: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum HttpOutcome { + Json(String), + NoContent, +} + +/// Entry point for `termherd mcp-proxy`. +/// +/// `config_path` comes from `TERMHERD_MCP_CONFIG` read once in `main()`. +/// Returns `Ok(())` on clean EOF, or `Err(diagnostic)` when a configured bridge +/// file cannot be loaded. +pub(crate) fn run(config_path: Option<&Path>, settings_path: Option<&Path>) -> Result<(), String> { + let stdin = io::stdin(); + let stdout = io::stdout(); + match config_path { + Some(path) => { + let target = read_config(path).map_err(|err| err.to_string())?; + serve_bridge(stdin.lock(), stdout.lock(), &target); + Ok(()) + } + None => { + let _ = writeln!( + io::stderr(), + "termherd mcp-proxy: {} is not set; live workspace tools are unavailable \ + (serving settings.json tools only)", + termherd_core::locations::MCP_CONFIG_VAR + ); + serve_settings_only(stdin.lock(), stdout.lock(), settings_path); + Ok(()) + } + } +} + +/// Parse the `mcpServers.termherd` entry written by +/// [`termherd_claude::mcp::servers_config`]. +pub(crate) fn read_config(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| ProxyConfigError::Io { + path: path.display().to_string(), + source, + })?; + parse_config(&text) +} + +pub(crate) fn parse_config(text: &str) -> Result { + let value: Value = serde_json::from_str(text)?; + let server = value + .get("mcpServers") + .and_then(|servers| servers.get("termherd")) + .ok_or(ProxyConfigError::MissingServer)?; + let url = server + .get("url") + .and_then(Value::as_str) + .ok_or(ProxyConfigError::MissingServer)?; + let (addr, host_header, path) = parse_loopback_url(url)?; + let auth = server + .get("headers") + .and_then(|headers| headers.get("Authorization")) + .and_then(Value::as_str) + .ok_or(ProxyConfigError::MissingToken)?; + let token = auth + .strip_prefix("Bearer ") + .filter(|t| !t.is_empty() && !t.contains('\r') && !t.contains('\n')) + .ok_or(ProxyConfigError::MissingToken)?; + Ok(BridgeTarget { + addr, + host_header, + path, + token: token.to_owned(), + }) +} + +fn parse_loopback_url(url: &str) -> Result<(SocketAddr, String, String), ProxyConfigError> { + let rest = url + .strip_prefix("http://") + .ok_or_else(|| ProxyConfigError::InvalidUrl(url.to_owned()))?; + let (authority, path) = match rest.find('/') { + Some(idx) => (&rest[..idx], &rest[idx..]), + None => (rest, "/"), + }; + if path.contains('\r') || path.contains('\n') || path.contains(' ') { + return Err(ProxyConfigError::InvalidUrl(url.to_owned())); + } + let (host, port_str) = authority + .rsplit_once(':') + .ok_or_else(|| ProxyConfigError::InvalidUrl(url.to_owned()))?; + let port: u16 = port_str + .parse() + .map_err(|_| ProxyConfigError::InvalidUrl(url.to_owned()))?; + let ip = match host { + "127.0.0.1" | "localhost" => IpAddr::V4(Ipv4Addr::LOCALHOST), + "[::1]" => IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + _ => return Err(ProxyConfigError::InvalidUrl(url.to_owned())), + }; + Ok(( + SocketAddr::new(ip, port), + format!("{host}:{port}"), + path.to_owned(), + )) +} + +/// Forward newline-delimited JSON-RPC messages on `reader` to `target` and +/// write replies to `writer`. +pub(crate) fn serve_bridge(reader: R, mut writer: W, target: &BridgeTarget) { + for line in reader.lines() { + let Ok(line) = line else { break }; + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + let Ok(message) = serde_json::from_str::(trimmed) else { + continue; + }; + let reply = match post_json(target, trimmed) { + Ok(HttpOutcome::Json(body)) => Some(compact_single_line(&body)), + Ok(HttpOutcome::NoContent) => None, + Err(err) => { + let _ = writeln!(io::stderr(), "termherd mcp-proxy: {err}"); + jsonrpc_error_response(&message, &err.to_string()).map(|v| v.to_string()) + } + }; + if let Some(reply) = reply { + if writeln!(writer, "{reply}").is_err() { + break; + } + if writer.flush().is_err() { + break; + } + } + } +} + +/// Serve the `settings.json` surface when `TERMHERD_MCP_CONFIG` is absent, +/// injecting [`MISSING_ENV_INSTRUCTIONS`] into `initialize` so the missing +/// live bridge is never silent. +pub(crate) fn serve_settings_only( + reader: R, + mut writer: W, + settings_path: Option<&Path>, +) { + for line in reader.lines() { + let Ok(line) = line else { break }; + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + let Ok(message) = serde_json::from_str::(trimmed) else { + continue; + }; + let (settings, writable) = match settings_path { + Some(path) => match termherd_mcp::file::read_object(path) { + Ok(value) => (value, Ok(())), + Err(reason) => (json!({}), Err(reason)), + }, + None => (json!({}), Ok(())), + }; + let reply = termherd_mcp::handle_message(&message, &settings); + let mut response = reply.response; + if message.get("method").and_then(Value::as_str) == Some("initialize") + && let Some(Value::Object(ref mut obj)) = response + && let Some(Value::Object(result)) = obj.get_mut("result") + { + result.insert( + "instructions".to_owned(), + Value::String(MISSING_ENV_INSTRUCTIONS.to_owned()), + ); + } + if let Some(new_settings) = reply.write_settings + && let Err(err) = writable.and_then(|()| { + let path = settings_path.ok_or("no home directory; cannot write settings")?; + termherd_mcp::file::write(path, &new_settings) + }) + { + let _ = writeln!(io::stderr(), "termherd mcp-proxy: {err}"); + response = + jsonrpc_error_response(&message, &format!("could not persist settings: {err}")); + } + if let Some(response) = response { + if writeln!(writer, "{response}").is_err() { + break; + } + if writer.flush().is_err() { + break; + } + } + } +} + +fn post_json(target: &BridgeTarget, body: &str) -> Result { + let mut stream = + TcpStream::connect_timeout(&target.addr, CONNECT_TIMEOUT).map_err(|source| { + TransportError::Connect { + addr: target.addr, + source, + } + })?; + stream.set_write_timeout(Some(WRITE_TIMEOUT))?; + stream.set_read_timeout(Some(READ_TIMEOUT))?; + + let request = format!( + "POST {path} HTTP/1.1\r\n\ + Host: {host}\r\n\ + Authorization: Bearer {token}\r\n\ + Content-Type: application/json\r\n\ + Accept: application/json, text/event-stream\r\n\ + Content-Length: {len}\r\n\ + Connection: close\r\n\ + \r\n\ + {body}", + path = target.path, + host = target.host_header, + token = target.token, + len = body.len(), + ); + stream.write_all(request.as_bytes())?; + stream.flush()?; + + let mut reader = BufReader::new(stream); + let (status, content_length, chunked) = read_response_head(&mut reader)?; + let raw_body = read_response_body(&mut reader, content_length, chunked)?; + let text = String::from_utf8(raw_body) + .map_err(|err| TransportError::MalformedHttp(err.to_string()))?; + + match status { + 200..=299 => { + if text.trim().is_empty() { + Ok(HttpOutcome::NoContent) + } else { + Ok(HttpOutcome::Json(text)) + } + } + 401 | 403 => Err(TransportError::Unauthorized(status)), + _ => Err(TransportError::HttpStatus { status, body: text }), + } +} + +fn read_response_head( + reader: &mut R, +) -> Result<(u16, Option, bool), TransportError> { + let mut status_line = String::new(); + let n = reader.read_line(&mut status_line)?; + if n == 0 { + return Err(TransportError::MalformedHttp( + "empty response from live bridge".to_owned(), + )); + } + let status: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|code| code.parse().ok()) + .ok_or_else(|| TransportError::MalformedHttp(status_line.trim().to_owned()))?; + + let mut header_bytes = n; + let mut content_length = None; + let mut chunked = false; + loop { + let mut line = String::new(); + let read = reader.read_line(&mut line)?; + if read == 0 { + break; + } + header_bytes += read; + if header_bytes > MAX_HEADER_BYTES { + return Err(TransportError::MalformedHttp( + "response headers exceeded limit".to_owned(), + )); + } + let trimmed = line.trim(); + if trimmed.is_empty() { + break; + } + if let Some((name, value)) = trimmed.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + content_length = value.trim().parse().ok(); + } else if name.eq_ignore_ascii_case("transfer-encoding") + && value.to_ascii_lowercase().contains("chunked") + { + chunked = true; + } + } + } + Ok((status, content_length, chunked)) +} + +fn read_response_body( + reader: &mut R, + content_length: Option, + chunked: bool, +) -> Result, TransportError> { + if chunked { + return read_chunked_body(reader); + } + if let Some(len) = content_length { + if len > MAX_BODY_BYTES { + return Err(TransportError::MalformedHttp( + "response body exceeded limit".to_owned(), + )); + } + let mut buf = vec![0u8; len]; + reader.read_exact(&mut buf)?; + return Ok(buf); + } + let mut buf = Vec::new(); + reader + .take((MAX_BODY_BYTES + 1) as u64) + .read_to_end(&mut buf)?; + if buf.len() > MAX_BODY_BYTES { + return Err(TransportError::MalformedHttp( + "response body exceeded limit".to_owned(), + )); + } + Ok(buf) +} + +fn read_chunked_body(reader: &mut R) -> Result, TransportError> { + let mut out = Vec::new(); + loop { + let mut size_line = String::new(); + if reader.read_line(&mut size_line)? == 0 { + return Err(TransportError::MalformedHttp( + "unexpected EOF in chunked body".to_owned(), + )); + } + let hex = size_line.trim().split(';').next().unwrap_or("").trim(); + let size = usize::from_str_radix(hex, 16) + .map_err(|_| TransportError::MalformedHttp(format!("bad chunk size: {hex}")))?; + if size == 0 { + break; + } + if out.len().saturating_add(size) > MAX_BODY_BYTES { + return Err(TransportError::MalformedHttp( + "chunked response body exceeded limit".to_owned(), + )); + } + let start = out.len(); + out.resize(start + size, 0); + reader.read_exact(&mut out[start..])?; + let mut crlf = [0u8; 2]; + reader.read_exact(&mut crlf)?; + } + Ok(out) +} + +fn compact_single_line(body: &str) -> String { + match serde_json::from_str::(body) { + Ok(value) => value.to_string(), + Err(_) => body.trim().replace(['\r', '\n'], " "), + } +} + +fn jsonrpc_error_response(message: &Value, detail: &str) -> Option { + let id = message.get("id")?; + Some(json!({ + "jsonrpc": "2.0", + "id": id, + "error": { + "code": -32000, + "message": format!("termherd live bridge error: {detail}"), + } + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_config_roundtrips_servers_config() { + let raw = termherd_claude::mcp::servers_config("http://127.0.0.1:52431/mcp", "secret123"); + let target = parse_config(&raw).expect("valid config"); + assert_eq!(target.addr, SocketAddr::from(([127, 0, 0, 1], 52431))); + assert_eq!(target.host_header, "127.0.0.1:52431"); + assert_eq!(target.path, "/mcp"); + assert_eq!(target.token, "secret123"); + } + + #[test] + fn parse_config_rejects_non_loopback_url_and_missing_token() { + let remote = termherd_claude::mcp::servers_config("http://192.168.1.5:52431/mcp", "tok"); + assert!(matches!( + parse_config(&remote), + Err(ProxyConfigError::InvalidUrl(_)) + )); + + let no_token = + r#"{"mcpServers":{"termherd":{"type":"http","url":"http://127.0.0.1:52431/mcp"}}}"#; + assert!(matches!( + parse_config(no_token), + Err(ProxyConfigError::MissingToken) + )); + } + + #[test] + fn read_chunked_body_reassembles_chunks() { + let wire = b"5\r\n{\"a\":\r\n2\r\n1}\r\n0\r\n\r\n"; + let mut cursor = io::Cursor::new(&wire[..]); + let decoded = read_chunked_body(&mut cursor).expect("chunked body"); + assert_eq!(decoded, br#"{"a":1}"#); + } + + #[test] + fn settings_only_initialize_explains_why_live_tools_are_missing() { + let input = concat!( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}"#, + "\n" + ); + let mut output = Vec::new(); + serve_settings_only(io::Cursor::new(input.as_bytes()), &mut output, None); + let line = String::from_utf8(output).expect("utf8"); + let resp: Value = serde_json::from_str(line.trim()).expect("json response"); + let instructions = resp["result"]["instructions"] + .as_str() + .expect("explicit instructions"); + assert!( + instructions.contains("TERMHERD_MCP_CONFIG"), + "instructions must name the missing env var, got: {instructions}" + ); + } + + #[tokio::test] + async fn proxy_forwards_initialize_and_tools_list_to_real_live_bridge() { + let (bridge, _requests) = crate::shell::bridge::channel(); + let tokens = crate::mcp::Tokens::default(); + let endpoint = crate::mcp::serve(bridge, tokens.clone(), None) + .await + .expect("bind loopback server"); + let token = tokens.issue(); + let config_json = termherd_claude::mcp::servers_config(&endpoint.url, &token); + let target = parse_config(&config_json).expect("parse config"); + + let input = concat!( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}"#, + "\n", + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + "\n", + r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#, + "\n" + ); + + let output = tokio::task::spawn_blocking(move || { + let mut out = Vec::new(); + serve_bridge(io::Cursor::new(input.as_bytes()), &mut out, &target); + String::from_utf8(out).expect("utf8") + }) + .await + .expect("join"); + + let lines: Vec<&str> = output.lines().collect(); + assert_eq!( + lines.len(), + 2, + "initialize and tools/list reply; notification emits nothing: {output}" + ); + let init: Value = serde_json::from_str(lines[0]).expect("init json"); + assert_eq!(init["id"], 1); + assert!(init["result"]["serverInfo"].is_object()); + + let list: Value = serde_json::from_str(lines[1]).expect("tools/list json"); + assert_eq!(list["id"], 2); + let names: Vec<&str> = list["result"]["tools"] + .as_array() + .expect("tools array") + .iter() + .filter_map(|t| t["name"].as_str()) + .collect(); + assert!(names.contains(&"snapshot"), "missing snapshot: {names:?}"); + assert!( + names.contains(&"list_sessions"), + "missing list_sessions: {names:?}" + ); + assert!( + names.contains(&"read_terminal"), + "missing read_terminal: {names:?}" + ); + } + + #[tokio::test] + async fn proxy_returns_jsonrpc_error_when_token_is_revoked() { + let (bridge, _requests) = crate::shell::bridge::channel(); + let tokens = crate::mcp::Tokens::default(); + let endpoint = crate::mcp::serve(bridge, tokens.clone(), None) + .await + .expect("bind loopback server"); + let token = tokens.issue(); + tokens.revoke(&token); + let config_json = termherd_claude::mcp::servers_config(&endpoint.url, &token); + let target = parse_config(&config_json).expect("parse config"); + + let input = concat!( + r#"{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}"#, + "\n" + ); + let output = tokio::task::spawn_blocking(move || { + let mut out = Vec::new(); + serve_bridge(io::Cursor::new(input.as_bytes()), &mut out, &target); + String::from_utf8(out).expect("utf8") + }) + .await + .expect("join"); + + let resp: Value = serde_json::from_str(output.trim()).expect("json error"); + assert_eq!(resp["id"], 7); + assert!( + resp["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("401")), + "expected 401 in error message, got: {resp}" + ); + } +} diff --git a/crates/app/src/paths.rs b/crates/app/src/paths.rs index f60e026..132a337 100644 --- a/crates/app/src/paths.rs +++ b/crates/app/src/paths.rs @@ -21,6 +21,13 @@ pub fn home_dir() -> Option { locations::home(&process_env) } +/// Per-session live-bridge config path from `$TERMHERD_MCP_CONFIG`, read in +/// `main()` alone for `termherd mcp-proxy`. +#[must_use] +pub fn mcp_config_path() -> Option { + locations::mcp_config_path(&process_env) +} + /// The app data dir (PRD §7). Resolved in `main()` alone and injected. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DataDir(PathBuf); @@ -228,6 +235,7 @@ mod tests { .env_remove(locations::DATA_DIR_VAR) .env_remove(locations::CLAUDE_CONFIG_DIR_VAR) .env_remove(locations::ANTIGRAVITY_DIR_VAR) + .env_remove(locations::MCP_CONFIG_VAR) .env("TMPDIR", tmp.path()) .env("TMP", tmp.path()) .env("TEMP", tmp.path()) diff --git a/crates/app/src/shell.rs b/crates/app/src/shell.rs index d06b2e2..d93df0d 100644 --- a/crates/app/src/shell.rs +++ b/crates/app/src/shell.rs @@ -7667,6 +7667,28 @@ mod key_routing { ); } + #[test] + fn an_antigravity_spawn_gets_an_mcp_config_and_a_revocable_token() { + let (mut shell, _pty) = empty_shell(); + shell.mcp_endpoint = Some(crate::mcp::Endpoint { + url: "http://127.0.0.1:9/mcp".into(), + }); + let session = session_id(2); + let mut spec = bare_spawn( + session, + Launch::agent_fresh(termherd_core::Provider::Antigravity, None), + ); + + shell.attach_mcp(&mut spec); + + let config = spec + .mcp + .expect("an Antigravity spawn carries an mcp config"); + assert_eq!(config.url, "http://127.0.0.1:9/mcp"); + assert!(!config.token.is_empty()); + assert!(shell.mcp_session_tokens.contains_key(&session)); + } + #[test] fn a_shell_spawn_never_gets_an_mcp_config() { let (mut shell, _pty) = empty_shell(); diff --git a/crates/core/src/locations.rs b/crates/core/src/locations.rs index 9259421..e0f7bc0 100644 --- a/crates/core/src/locations.rs +++ b/crates/core/src/locations.rs @@ -25,6 +25,11 @@ pub const CLAUDE_CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR"; /// real conversations. pub const ANTIGRAVITY_DIR_VAR: &str = "TERMHERD_ANTIGRAVITY_DIR"; +/// Path to the per-session private `mcpServers` config file exported into an +/// agent session's PTY environment so `termherd mcp-proxy` can forward stdio +/// MCP traffic to the parent instance's live bridge. +pub const MCP_CONFIG_VAR: &str = "TERMHERD_MCP_CONFIG"; + /// The user's home directory: `%USERPROFILE%` (Windows) then `$HOME` (Unix). /// `None` when neither is set. #[must_use] @@ -54,6 +59,13 @@ pub fn antigravity_dir(env: &impl Fn(&str) -> Option) -> Option Option) -> Option { + overridden(env, MCP_CONFIG_VAR) +} + fn overridden(env: &impl Fn(&str) -> Option, name: &str) -> Option { env(name) .filter(|value| !value.is_empty()) @@ -154,4 +166,14 @@ mod tests { Some(PathBuf::from("/h/.gemini/antigravity-cli")) ); } + + #[test] + fn mcp_config_path_reads_only_its_own_non_empty_var() { + assert_eq!(mcp_config_path(&env_of(&[("HOME", "/h")])), None); + assert_eq!(mcp_config_path(&env_of(&[(MCP_CONFIG_VAR, "")])), None); + assert_eq!( + mcp_config_path(&env_of(&[(MCP_CONFIG_VAR, "/tmp/termherd-mcp-1.json")])), + Some(PathBuf::from("/tmp/termherd-mcp-1.json")) + ); + } } diff --git a/crates/core/src/provider.rs b/crates/core/src/provider.rs index 2c5564f..93806ec 100644 --- a/crates/core/src/provider.rs +++ b/crates/core/src/provider.rs @@ -153,7 +153,7 @@ impl Provider { agent_name: false, send_to_desktop: false, reveal_transcript: true, - mcp_bridge_injection: false, + mcp_bridge_injection: true, }, } } @@ -265,10 +265,11 @@ mod tests { assert!(!caps.slash_commands); assert!(!caps.agent_name); assert!(!caps.send_to_desktop); - assert!(!caps.mcp_bridge_injection); } assert!(Provider::Antigravity.capabilities().launch_supported); + assert!(Provider::Antigravity.capabilities().mcp_bridge_injection); assert!(!Provider::Codex.capabilities().launch_supported); + assert!(!Provider::Codex.capabilities().mcp_bridge_injection); } #[test] diff --git a/crates/pty/src/launch.rs b/crates/pty/src/launch.rs index da0f6d2..5060f10 100644 --- a/crates/pty/src/launch.rs +++ b/crates/pty/src/launch.rs @@ -355,6 +355,30 @@ pub(crate) fn strip_inherited_session_env(cmd: &mut CommandBuilder) { } } +/// TermHerd's own per-session environment variables. Stripped before every +/// spawn so a plain shell or a nested TermHerd instance never inherits an +/// outer session's live-bridge pointer; agent launches that own a bridge +/// re-export their own path via [`apply_mcp_config_env`]. +pub(crate) const TERMHERD_SESSION_VARS: &[&str] = &[termherd_core::locations::MCP_CONFIG_VAR]; + +/// Remove every [`TERMHERD_SESSION_VARS`] entry from what `cmd` will spawn +/// with. +pub(crate) fn strip_termherd_session_env(cmd: &mut CommandBuilder) { + for name in TERMHERD_SESSION_VARS { + cmd.env_remove(name); + } +} + +/// Export the session's private `mcpServers` file path into the spawned PTY +/// environment so CLIs without a `--mcp-config` flag (such as Antigravity) can +/// reach the parent instance's live bridge through `termherd mcp-proxy`. The +/// file — not the environment — holds the bearer token. +pub(crate) fn apply_mcp_config_env(cmd: &mut CommandBuilder, mcp_config: Option<&Path>) { + if let Some(path) = mcp_config { + cmd.env(termherd_core::locations::MCP_CONFIG_VAR, path); + } +} + #[cfg(test)] mod tests { use super::*; @@ -445,6 +469,47 @@ mod tests { } } + #[test] + fn stripping_termherd_session_env_removes_mcp_config_var() { + let mut cmd = CommandBuilder::new("/bin/sh"); + cmd.env( + termherd_core::locations::MCP_CONFIG_VAR, + "/tmp/parent-mcp.json", + ); + cmd.env("TERMHERD_DATA_DIR", "/tmp/data"); + strip_termherd_session_env(&mut cmd); + assert!( + cmd.get_env(termherd_core::locations::MCP_CONFIG_VAR) + .is_none(), + "parent TERMHERD_MCP_CONFIG must not leak into child spawns" + ); + assert_eq!( + cmd.get_env("TERMHERD_DATA_DIR"), + Some("/tmp/data".as_ref()), + "unrelated TERMHERD_* vars stay intact" + ); + } + + #[test] + fn apply_mcp_config_env_exports_only_when_present() { + let mut without = CommandBuilder::new("/bin/sh"); + strip_termherd_session_env(&mut without); + apply_mcp_config_env(&mut without, None); + assert!( + without + .get_env(termherd_core::locations::MCP_CONFIG_VAR) + .is_none() + ); + + let mut with = CommandBuilder::new("/bin/sh"); + strip_termherd_session_env(&mut with); + apply_mcp_config_env(&mut with, Some(mcp())); + assert_eq!( + with.get_env(termherd_core::locations::MCP_CONFIG_VAR), + Some(mcp().as_os_str()) + ); + } + mod stripping { use proptest::prelude::*; diff --git a/crates/pty/src/manager.rs b/crates/pty/src/manager.rs index ffdead6..b4e0118 100644 --- a/crates/pty/src/manager.rs +++ b/crates/pty/src/manager.rs @@ -18,8 +18,9 @@ use crate::events::EventSink; use crate::grid::Palette; use crate::kill::finish_kill; use crate::launch::{ - PrivateFiles, apply_integration, apply_terminal_env, discard_private_files, launch_command, - strip_inherited_session_env, write_mcp_config, write_title_settings, + PrivateFiles, apply_integration, apply_mcp_config_env, apply_terminal_env, + discard_private_files, launch_command, strip_inherited_session_env, strip_termherd_session_env, + write_mcp_config, write_title_settings, }; use crate::session::{ SCREEN_INTERVAL, Session, SharedMaster, SharedPalette, SharedWriter, TermCmd, spawn_reader, @@ -141,6 +142,7 @@ fn shell_command(configured: Option<&Shell>, cwd: Option<&str>) -> CommandBuilde cmd.cwd(cwd); } strip_inherited_session_env(&mut cmd); + strip_termherd_session_env(&mut cmd); apply_terminal_env(&mut cmd); cmd } @@ -183,6 +185,7 @@ impl PtyHost for PtyManager { .mcp .as_ref() .and_then(|config| write_mcp_config(&self.private, spec.session, config)); + apply_mcp_config_env(&mut cmd, mcp_config_path.as_deref()); let child = match pair.slave.spawn_command(cmd) { Ok(child) => child, diff --git a/docs/src/mcp/live-bridge.md b/docs/src/mcp/live-bridge.md index b980ef9..6c5eb3b 100644 --- a/docs/src/mcp/live-bridge.md +++ b/docs/src/mcp/live-bridge.md @@ -17,6 +17,25 @@ A client TermHerd did **not** launch can reach the same server, and the same tools, once the instance is told to publish its address — see [Attaching from outside](./attach.md). Everything below applies unchanged there. +## Antigravity (`agy`) and CLIs without `--mcp-config` + +Every agent session TermHerd spawns also receives `TERMHERD_MCP_CONFIG` in its +PTY environment, pointing to that session's private `0600` `mcpServers` file +(the bearer token stays in the file, never in the environment). Register +`termherd mcp-proxy` once in Antigravity so every session launched from +TermHerd gets the same live tools: + +```bash +agy mcp add termherd /path/to/termherd mcp-proxy +``` + +When `TERMHERD_MCP_CONFIG` is present, `termherd mcp-proxy` forwards stdio +JSON-RPC to that session's loopback bridge and surfaces transport or token +errors directly as JSON-RPC errors. When `TERMHERD_MCP_CONFIG` is absent +(launched outside TermHerd, or a host CLI that does not propagate it), it +serves the `settings.json` tools (`list_options`, `set_option`) and states in +its `initialize` instructions why the live workspace tools are unavailable. + ## The tools ### Perception From 29e3a5a796bf06cf4abedb2778a237a58d54060f Mon Sep 17 00:00:00 2001 From: Bastien Gallay Date: Mon, 23 Nov 2026 08:02:38 +0100 Subject: [PATCH 3/3] fix(mcp): bound HTTP header line reads and scope live-bridge error prefix --- crates/app/src/mcp_proxy.rs | 65 ++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 19 deletions(-) diff --git a/crates/app/src/mcp_proxy.rs b/crates/app/src/mcp_proxy.rs index e186272..37a9dfb 100644 --- a/crates/app/src/mcp_proxy.rs +++ b/crates/app/src/mcp_proxy.rs @@ -206,7 +206,8 @@ pub(crate) fn serve_bridge(reader: R, mut writer: W, targe Ok(HttpOutcome::NoContent) => None, Err(err) => { let _ = writeln!(io::stderr(), "termherd mcp-proxy: {err}"); - jsonrpc_error_response(&message, &err.to_string()).map(|v| v.to_string()) + jsonrpc_error_response(&message, &format!("termherd live bridge error: {err}")) + .map(|v| v.to_string()) } }; if let Some(reply) = reply { @@ -324,37 +325,45 @@ fn post_json(target: &BridgeTarget, body: &str) -> Result( + reader: &mut R, + remaining: usize, +) -> Result, TransportError> { + let mut buf = Vec::new(); + let limit = remaining.saturating_add(1) as u64; + let read = reader.by_ref().take(limit).read_until(b'\n', &mut buf)?; + if read == 0 { + return Ok(None); + } + if read > remaining { + return Err(TransportError::MalformedHttp( + "response headers exceeded limit".to_owned(), + )); + } + String::from_utf8(buf) + .map(Some) + .map_err(|err| TransportError::MalformedHttp(err.to_string())) +} + fn read_response_head( reader: &mut R, ) -> Result<(u16, Option, bool), TransportError> { - let mut status_line = String::new(); - let n = reader.read_line(&mut status_line)?; - if n == 0 { + let Some(status_line) = read_bounded_line(reader, MAX_HEADER_BYTES)? else { return Err(TransportError::MalformedHttp( "empty response from live bridge".to_owned(), )); - } + }; let status: u16 = status_line .split_whitespace() .nth(1) .and_then(|code| code.parse().ok()) .ok_or_else(|| TransportError::MalformedHttp(status_line.trim().to_owned()))?; - let mut header_bytes = n; + let mut header_bytes = status_line.len(); let mut content_length = None; let mut chunked = false; - loop { - let mut line = String::new(); - let read = reader.read_line(&mut line)?; - if read == 0 { - break; - } - header_bytes += read; - if header_bytes > MAX_HEADER_BYTES { - return Err(TransportError::MalformedHttp( - "response headers exceeded limit".to_owned(), - )); - } + while let Some(line) = read_bounded_line(reader, MAX_HEADER_BYTES - header_bytes)? { + header_bytes += line.len(); let trimmed = line.trim(); if trimmed.is_empty() { break; @@ -445,7 +454,7 @@ fn jsonrpc_error_response(message: &Value, detail: &str) -> Option { "id": id, "error": { "code": -32000, - "message": format!("termherd live bridge error: {detail}"), + "message": detail, } })) } @@ -488,6 +497,24 @@ mod tests { assert_eq!(decoded, br#"{"a":1}"#); } + #[test] + fn read_response_head_bounds_a_line_without_a_newline() { + let huge = vec![b'x'; MAX_HEADER_BYTES + 128]; + let mut cursor = io::Cursor::new(&huge[..]); + assert!(matches!( + read_response_head(&mut cursor), + Err(TransportError::MalformedHttp(_)) + )); + } + + #[test] + fn run_fails_loudly_when_configured_file_is_missing() { + let dir = tempfile::tempdir().expect("tempdir"); + let missing = dir.path().join("does-not-exist.json"); + let err = run(Some(&missing), None).expect_err("must not fall back to settings"); + assert!(err.contains("could not read"), "got: {err}"); + } + #[test] fn settings_only_initialize_explains_why_live_tools_are_missing() { let input = concat!(