Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(server): the window's server lists itself for local callers, and a blocking client for it (#337)

Jareer56ff055a8a26
diff --git a/src/crates/concat-server/Cargo.toml b/src/crates/concat-server/Cargo.toml
index 3f3e96b4..9acb2a66 100644
--- a/src/crates/concat-server/Cargo.toml
+++ b/src/crates/concat-server/Cargo.toml
@@ -24,6 +24,8 @@ grpc = [
[dependencies]
concat-api.workspace = true
serde_json.workspace = true
+# The listing a local MCP adapter reads to find the window's server.
+serde = { version = "1", features = ["derive"] }
# A token minted when none was given: 128 bits the operating system
# hands out, so the server is never open to whoever reaches the socket.
getrandom = "0.3"
diff --git a/src/crates/concat-server/src/client.rs b/src/crates/concat-server/src/client.rs
new file mode 100644
index 00000000..0d835d1b
--- /dev/null
+++ b/src/crates/concat-server/src/client.rs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The other end of [`crate::json`]: a blocking JSON-RPC line client, for a
+//! process that drives a running server - the MCP adapter going through
+//! the window, a test.
+//!
+//! One call at a time. The events the server sends between replies are
+//! not the client's business here - a caller that wants to follow a job
+//! asks `export.status` - so they are read past and dropped.
+
+use std::io::{BufRead, BufReader, Write};
+use std::net::{SocketAddr, TcpStream};
+use std::time::Duration;
+
+use concat_api::{ApiError, ErrorCode, Request};
+use serde_json::{Value, json};
+
+/// The longest reply line read: a project's whole document fits, and an
+/// inline 8K frame.
+const MAX_REPLY: u64 = 256 * 1024 * 1024;
+
+/// A connection to a server, its token presented.
+pub struct Client {
+ reader: BufReader<TcpStream>,
+ writer: TcpStream,
+ next_id: u64,
+ address: SocketAddr,
+}
+
+impl Client {
+ /// Connects to `address` and presents `token`. `patience` bounds the
+ /// connect and the handshake, not the calls after it, which take as
+ /// long as their method does.
+ pub fn connect(address: SocketAddr, token: &str, patience: Duration) -> Result<Client, String> {
+ let could_not = |error: &dyn std::fmt::Display| {
+ format!("could not reach the Concat server at {address}: {error}")
+ };
+ let stream =
+ TcpStream::connect_timeout(&address, patience).map_err(|error| could_not(&error))?;
+ let _ = stream.set_nodelay(true);
+ stream
+ .set_read_timeout(Some(patience))
+ .map_err(|error| could_not(&error))?;
+ let writer = stream.try_clone().map_err(|error| could_not(&error))?;
+ let mut client = Client {
+ reader: BufReader::new(stream),
+ writer,
+ next_id: 1,
+ address,
+ };
+ client
+ .exchange("auth", json!({ "token": token }))
+ .map_err(|error| could_not(&error))?;
+ client
+ .reader
+ .get_ref()
+ .set_read_timeout(None)
+ .map_err(|error| could_not(&error))?;
+ Ok(client)
+ }
+
+ /// Where this client is connected.
+ pub fn address(&self) -> SocketAddr {
+ self.address
+ }
+
+ /// Runs one request and returns its result, as the JSON the server
+ /// sent.
+ pub fn call(&mut self, request: &Request) -> Result<Value, ApiError> {
+ let Value::Object(mut fields) = serde_json::to_value(request)
+ .map_err(|error| ApiError::invalid(format!("not a request: {error}")))?
+ else {
+ return Err(ApiError::invalid("a request is an object"));
+ };
+ let method = match fields.remove("method") {
+ Some(Value::String(method)) => method,
+ _ => return Err(ApiError::invalid("a request names its method")),
+ };
+ self.exchange(&method, Value::Object(fields))
+ }
+
+ /// Sends one call and reads lines until its reply.
+ fn exchange(&mut self, method: &str, params: Value) -> Result<Value, ApiError> {
+ let id = self.next_id;
+ self.next_id += 1;
+ let line = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
+ let gone = |error: &dyn std::fmt::Display| {
+ ApiError::failed(format!("the connection to the Concat server failed: {error}"))
+ };
+ writeln!(self.writer, "{line}").map_err(|error| gone(&error))?;
+ self.writer.flush().map_err(|error| gone(&error))?;
+ loop {
+ let mut reply = String::new();
+ let read = std::io::Read::take(&mut self.reader, MAX_REPLY)
+ .read_line(&mut reply)
+ .map_err(|error| gone(&error))?;
+ if read == 0 {
+ return Err(gone(&"the server hung up"));
+ }
+ let Ok(Value::Object(mut message)) = serde_json::from_str::<Value>(&reply) else {
+ return Err(gone(&"the server sent something that is not JSON-RPC"));
+ };
+ // An event, or the refusal of a connection the server never
+ // let in (null id): the latter is the answer.
+ let answered = match message.get("id") {
+ Some(Value::Number(number)) => number.as_u64() == Some(id),
+ Some(Value::Null) => message.contains_key("error"),
+ _ => false,
+ };
+ if !answered {
+ continue;
+ }
+ if let Some(result) = message.remove("result") {
+ return Ok(result);
+ }
+ let error = message.remove("error").unwrap_or(Value::Null);
+ let code = error
+ .pointer("/data/code")
+ .cloned()
+ .and_then(|code| serde_json::from_value::<ErrorCode>(code).ok())
+ .unwrap_or(ErrorCode::Failed);
+ let text = error
+ .get("message")
+ .and_then(Value::as_str)
+ .unwrap_or("the server refused the call");
+ return Err(ApiError::new(code, text));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::tests::server;
+
+ #[test]
+ fn a_client_presents_its_token_and_calls_through_events() {
+ let (server, scratch) = server(None);
+ let address = server.json_addr().expect("listening");
+ let wrong = Client::connect(address, "not the token, not at all", Duration::from_secs(5));
+ assert!(wrong.is_err());
+ let mut client =
+ Client::connect(address, server.token(), Duration::from_secs(5)).expect("in");
+ let version = client.call(&Request::Version).expect("answers");
+ assert_eq!(version["apiVersion"], concat_api::API_VERSION);
+ let location = scratch.path().to_string_lossy().into_owned();
+ let created = client
+ .call(&Request::ProjectCreate {
+ location,
+ name: "Remote".to_owned(),
+ video: None,
+ })
+ .expect("creates");
+ assert!(created["project"].is_object(), "{created}");
+ let refused = client
+ .call(&Request::ProjectGet {
+ path: "/nowhere".to_owned(),
+ })
+ .expect_err("not open");
+ assert_eq!(refused.code, ErrorCode::NotOpen);
+ drop(client);
+ server.stop();
+ }
+}
diff --git a/src/crates/concat-server/src/discovery.rs b/src/crates/concat-server/src/discovery.rs
new file mode 100644
index 00000000..561077f2
--- /dev/null
+++ b/src/crates/concat-server/src/discovery.rs
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! How a program on this machine finds the window's server: a small file
+//! in the app's config folder, written while the server runs and removed
+//! when it stops.
+//!
+//! The file is what an MCP adapter started by an agent reads - `concat
+//! --mcp`, launched by Claude Code or another client with no way to be
+//! told an address or a token - so it can go through the window's server
+//! rather than open projects behind the window's back. It holds the token,
+//! so it is written readable by its owner alone (0600 on Unix; on Windows
+//! the config folder's own per-user permissions), the way the preferences
+//! that may already hold a chosen token are. A file left by a window that
+//! crashed names a server that is no longer there; a reader finds that
+//! out by connecting, and [`Listing::pid`] lets it say why.
+//!
+//! ```json
+//! {"version": 1, "address": "127.0.0.1:7420", "token": "...",
+//! "pid": 4242, "concat": "0.2.7", "apiVersion": "0.2"}
+//! ```
+
+use std::io::Write;
+use std::net::SocketAddr;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+/// The file's name in the config folder.
+pub const FILE_NAME: &str = "automation.json";
+/// This layout. A reader refuses a file with another.
+pub const VERSION: u32 = 1;
+
+/// Where the listing is kept, under the app's config folder.
+pub fn path_in(config: &Path) -> PathBuf {
+ config.join(FILE_NAME)
+}
+
+/// What the file says.
+#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Listing {
+ /// [`VERSION`].
+ pub version: u32,
+ /// Where to connect: the JSON-RPC address, made reachable from this
+ /// machine - a server bound to every interface is reached on loopback.
+ pub address: SocketAddr,
+ /// The token to present.
+ pub token: String,
+ /// The process serving, for a reader that wants to tell a stale file
+ /// from a server that is busy.
+ pub pid: u32,
+ /// The Concat build serving.
+ pub concat: String,
+ /// The API contract it speaks.
+ pub api_version: String,
+}
+
+impl Listing {
+ /// A listing for a server bound to `bound`, in this process.
+ pub fn new(bound: SocketAddr, token: &str) -> Listing {
+ Listing {
+ version: VERSION,
+ address: crate::loopback(bound),
+ token: token.to_owned(),
+ pid: std::process::id(),
+ concat: env!("CARGO_PKG_VERSION").to_owned(),
+ api_version: concat_api::API_VERSION.to_owned(),
+ }
+ }
+}
+
+/// Writes `listing` to `path`, readable by its owner alone, replacing what
+/// was there in one step: written beside it and renamed over it, so a
+/// reader sees the old file or the new one and never half of either.
+pub fn write(path: &Path, listing: &Listing) -> Result<(), String> {
+ let could_not = |error: &dyn std::fmt::Display| {
+ format!("could not write {}: {error}", path.display())
+ };
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|error| could_not(&error))?;
+ }
+ let text = serde_json::to_string_pretty(listing).map_err(|error| could_not(&error))?;
+ let staging = path.with_extension(format!("json.{}", std::process::id()));
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let written = options
+ .open(&staging)
+ .and_then(|mut file| {
+ // The mode above applies to a file created now; one left from
+ // before with wider permissions is narrowed here.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
+ }
+ file.write_all(text.as_bytes())?;
+ file.sync_all()
+ })
+ .and_then(|()| std::fs::rename(&staging, path));
+ if let Err(error) = written {
+ let _ = std::fs::remove_file(&staging);
+ return Err(could_not(&error));
+ }
+ Ok(())
+}
+
+/// The listing at `path`: `None` when there is none, `Err` when there is
+/// one that cannot be read or is of another layout.
+pub fn read(path: &Path) -> Result<Option<Listing>, String> {
+ let text = match std::fs::read_to_string(path) {
+ Ok(text) => text,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(format!("could not read {}: {error}", path.display())),
+ };
+ let listing: Listing = serde_json::from_str(&text)
+ .map_err(|error| format!("{} is not a server listing: {error}", path.display()))?;
+ if listing.version != VERSION {
+ return Err(format!(
+ "{} is layout {}, and this build reads {VERSION}",
+ path.display(),
+ listing.version
+ ));
+ }
+ Ok(Some(listing))
+}
+
+/// Takes the listing away - but only one this process wrote, so a second
+/// window stopping its server does not unlist the first's.
+pub fn remove(path: &Path) {
+ if let Ok(Some(listing)) = read(path)
+ && listing.pid != std::process::id()
+ {
+ return;
+ }
+ let _ = std::fs::remove_file(path);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_listing_round_trips_owner_only_and_is_removed_by_its_writer() {
+ let scratch = tempfile::tempdir().expect("scratch");
+ let path = path_in(&scratch.path().join("config"));
+ assert_eq!(read(&path), Ok(None));
+ let listing = Listing::new("0.0.0.0:7420".parse().expect("an address"), "t0ken");
+ assert_eq!(listing.address, "127.0.0.1:7420".parse().expect("an address"));
+ write(&path, &listing).expect("writes");
+ assert_eq!(read(&path), Ok(Some(listing.clone())));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(&path).expect("there").permissions().mode();
+ assert_eq!(mode & 0o777, 0o600, "{mode:o}");
+ }
+ // Someone else's listing stays.
+ let theirs = Listing {
+ pid: listing.pid.wrapping_add(1),
+ ..listing.clone()
+ };
+ write(&path, &theirs).expect("writes");
+ remove(&path);
+ assert!(path.exists());
+ write(&path, &listing).expect("writes");
+ remove(&path);
+ assert!(!path.exists());
+ }
+
+ #[test]
+ fn a_file_of_another_layout_or_none_is_said_so() {
+ let scratch = tempfile::tempdir().expect("scratch");
+ let path = scratch.path().join(FILE_NAME);
+ std::fs::write(&path, "{").expect("writes");
+ assert!(read(&path).is_err());
+ let mut listing = Listing::new("[::]:1".parse().expect("an address"), "t");
+ assert_eq!(listing.address, "[::1]:1".parse().expect("an address"));
+ listing.version = VERSION + 1;
+ std::fs::write(&path, serde_json::to_string(&listing).expect("JSON")).expect("writes");
+ assert!(read(&path).expect_err("refused").contains("layout"));
+ }
+}
diff --git a/src/crates/concat-server/src/lib.rs b/src/crates/concat-server/src/lib.rs
index 06d91b74..63f03f20 100644
--- a/src/crates/concat-server/src/lib.rs
+++ b/src/crates/concat-server/src/lib.rs
@@ -40,6 +40,8 @@
//! encryption: a bind off loopback belongs behind something that provides
//! it, and [`is_exposed`] is how a front end says so.
+pub mod client;
+pub mod discovery;
mod hub;
pub mod json;
pub mod throttle;
@@ -117,6 +119,11 @@ pub struct Config {
/// instantiated template, an export, a preview file. Empty means the
/// user's home ([`home_root`]); to write anywhere, name `/`.
pub roots: Vec<PathBuf>,
+ /// Where to list the JSON-RPC address and the token while the server
+ /// runs, for a program on this machine to find it - `concat --mcp`,
+ /// started by an agent. See [`discovery`]; removed when the server
+ /// stops. `None` lists nothing.
+ pub discovery: Option<PathBuf>,
}
/// Where the API writes when told nothing else: the user's home folder,
@@ -165,6 +172,8 @@ pub struct Server {
connections: Connections,
seats: Arc<AtomicUsize>,
pending: Arc<AtomicUsize>,
+ /// The listing written for local callers, taken away at the stop.
+ listing: Option<PathBuf>,
}
/// Every connection that is in, by number, with its way of being closed,
@@ -237,6 +246,7 @@ impl Server {
connections: Arc::clone(&connections),
seats: Arc::clone(&door.seats),
pending: Arc::clone(&door.pending),
+ listing: None,
};
let could_not = |what: &str, error: &dyn std::fmt::Display| {
format!("could not listen on {what}: {error}")
@@ -282,6 +292,14 @@ impl Server {
}
let _ = throttle;
+ // Last, so nothing is listed that is not yet listening. A listing
+ // that cannot be written costs the agent a way in, not the server.
+ if let (Some(path), Some(address)) = (config.discovery, server.json)
+ && discovery::write(&path, &discovery::Listing::new(address, &server.token)).is_ok()
+ {
+ server.listing = Some(path);
+ }
+
Ok(server)
}
@@ -363,6 +381,10 @@ impl Server {
/// the listeners joined, the connections hung up, the jobs cancelled
/// and the queue closed.
fn close_doors(&mut self) {
+ // Unlisted first, so nobody new is sent to a door that is closing.
+ if let Some(path) = self.listing.take() {
+ discovery::remove(&path);
+ }
self.stop.store(true, Ordering::SeqCst);
// A blocked accept wakes for a connection; make one - to loopback
// when the bind was to every interface, which Windows refuses to
@@ -508,6 +530,29 @@ pub(crate) mod tests {
server.stop();
}
+ #[test]
+ fn a_server_lists_itself_while_it_runs() {
+ let scratch = tempfile::tempdir().expect("scratch");
+ let dirs = AppDirs {
+ config: scratch.path().join("config"),
+ data: scratch.path().join("data"),
+ };
+ let path = discovery::path_in(&dirs.config);
+ let config = Config {
+ json: Some("127.0.0.1:0".parse().expect("an address")),
+ roots: vec![scratch.path().to_path_buf()],
+ discovery: Some(path.clone()),
+ ..Config::default()
+ };
+ let server =
+ Server::start(config, move |events| Ok(Api::with_dirs(dirs, events))).expect("starts");
+ let listing = discovery::read(&path).expect("reads").expect("listed");
+ assert_eq!(Some(listing.address), server.json_addr());
+ assert_eq!(listing.token, server.token());
+ server.stop_detached();
+ assert!(!path.exists(), "unlisted at the stop");
+ }
+
#[test]
fn a_detached_stop_frees_the_address_at_once() {
let (server, _scratch) = server(None);