Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.
Rust ai-agentsclaude-codeclicodexcoding-agentskanbanlocal-firstmcpmcp-servermodel-context-protocolproductivityproject-managementraspberry-pirustself-hostedsqlitetask-manager
Send a joined computer's agents to the shared board
emanuele-em26171346d4b5
diff --git a/Cargo.toml b/Cargo.tomlindex d08f7b9..33c5fe7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -28,7 +28,7 @@ rusqlite = { version = "0.41.0", features = ["bundled"] }schemars = "1.2.3"serde = { version = "1.0.229", features = ["derive"] }serde_json = "1.0.154"-tokio = { version = "1.54.1", features = ["rt", "macros", "net", "signal", "io-util", "time"] }+tokio = { version = "1.54.1", features = ["rt", "macros", "net", "signal", "io-util", "sync", "time"] }tokio-util = { version = "0.7.20", features = ["io"] }# Kanzo reads config.toml and never writes TOML.toml = { version = "1.1.8", default-features = false, features = ["std", "parse", "serde"] }diff --git a/src/mcp.rs b/src/mcp.rsindex bdeb755..d0fceed 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -7,9 +7,15 @@ use std::process::Command;use std::sync::Arc;use anyhow::Result;+use axum::http::request::Parts;use rmcp::handler::server::router::tool::ToolRouter;+use rmcp::handler::server::tool::ToolCallContext;use rmcp::handler::server::wrapper::Parameters;-use rmcp::model::{CallToolResult, ContentBlock, Implementation, ServerCapabilities, ServerConfig};+use rmcp::model::{+ CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Extensions, Implementation,+ ServerCapabilities, ServerConfig,+};+use rmcp::service::RequestContext;use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};use rmcp::{ErrorData, Peer, RoleServer, ServerHandler, ServiceExt, tool, tool_handler, tool_router};@@ -18,6 +24,7 @@ use serde::Deserialize;use tokio_util::sync::CancellationToken;use crate::home::Home;+use crate::share::{self, Net};use crate::store::{self, Error, Project, Store, Task, TaskPatch, short_time};/// The most done tasks list_tasks shows, newest first: an old board has thousands.@@ -37,7 +44,8 @@ done and human tasks to the user.";pub async fn serve(home: Home) -> Result<()> {let cwd = std::env::current_dir().unwrap_or_default();let repos = git_repos(&cwd);- let server = Kanzo { ctx: Arc::new(Ctx { home, cwd: Some(cwd), repos }), tool_router: Kanzo::tools() };+ let ctx = Ctx { home, cwd: Some(cwd), repos, host: Default::default() };+ let server = Kanzo { ctx: Arc::new(ctx), tool_router: Kanzo::tools() };let service = server.serve(rmcp::transport::stdio()).await?;service.waiting().await?;Ok(())@@ -47,7 +55,7 @@ pub async fn serve(home: Home) -> Result<()> {/// checks (`web::protect`) guard it, including when it listens on the network, so/// rmcp's localhost-only list is turned off here.pub fn http_service(home: Home, shutdown: CancellationToken) -> StreamableHttpService<Kanzo, LocalSessionManager> {- let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new() });+ let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new(), host: Default::default() });let config = StreamableHttpServerConfig::default().disable_allowed_hosts().with_cancellation_token(shutdown);// rmcp makes a server per session, and for some requests; the tool list is built once.let tool_router = Kanzo::tools();@@ -64,6 +72,8 @@ struct Ctx {cwd: Option<PathBuf>,/// GitHub repos (`owner/repo`) of the git remotes of `cwd`.repos: Vec<String>,+ /// The board this computer joined, while `kanzo mcp` uses it for the agent.+ host: tokio::sync::Mutex<Option<share::Upstream>>,}impl Ctx {@@ -259,7 +269,34 @@ impl Kanzo {/// Runs `f` with a fresh connection on a blocking thread and turns the/// outcome into text; errors go back to the agent as tool errors it can read.async fn run(&self, f: impl FnOnce(&Ctx, &Store) -> store::Result<String> + Send + 'static) -> CallToolResult {- let ctx = self.ctx.clone();+ self.run_for(&Extensions::default(), f).await+ }++ /// Like `run`, with the agent's folder when `kanzo mcp` on a computer that joined+ /// this board sent it along with the message.+ async fn run_for(+ &self,+ ext: &Extensions,+ f: impl FnOnce(&Ctx, &Store) -> store::Result<String> + Send + 'static,+ ) -> CallToolResult {+ let header = |name| {+ let value = ext.get::<Parts>()?.headers.get(name)?;+ Some(String::from_utf8_lossy(value.as_bytes()).into_owned())+ };+ let ctx = match header(share::FOLDER_HEADER) {+ Some(folder) => Arc::new(Ctx {+ home: self.ctx.home.clone(),+ cwd: Some(folder.into()),+ repos: header(share::REPOS_HEADER)+ .unwrap_or_default()+ .split(',')+ .filter(|r| !r.is_empty())+ .map(String::from)+ .collect(),+ host: Default::default(),+ }),+ None => self.ctx.clone(),+ };let outcome = tokio::task::spawn_blocking(move || {let store = ctx.home.store().map_err(|e| e.to_string())?;f(&ctx, &store).map_err(|e| e.to_string())@@ -273,9 +310,9 @@ impl Kanzo {}#[tool(description = "List projects with their repos and open task counts.")]- async fn list_projects(&self) -> Result<CallToolResult, ErrorData> {+ async fn list_projects(&self, ext: Extensions) -> Result<CallToolResult, ErrorData> {Ok(self- .run(|ctx, store| {+ .run_for(&ext, |ctx, store| {let projects = store.list_projects()?;if projects.is_empty() {return Ok("No projects yet. Create one with create_project.".into());@@ -327,9 +364,13 @@ impl Kanzo {}#[tool(description = "List tasks in board order.")]- async fn list_tasks(&self, Parameters(args): Parameters<ListTasksArgs>) -> Result<CallToolResult, ErrorData> {+ async fn list_tasks(+ &self,+ Parameters(args): Parameters<ListTasksArgs>,+ ext: Extensions,+ ) -> Result<CallToolResult, ErrorData> {Ok(self- .run(move |ctx, store| {+ .run_for(&ext, move |ctx, store| {let all = args.project.as_deref().is_some_and(|p| p.trim().eq_ignore_ascii_case("all"));let project = if all { None } else { Some(ctx.project(store, args.project.as_deref())?) };let status = args.status.as_deref().map(str::trim).filter(|s| !s.is_empty());@@ -380,9 +421,13 @@ impl Kanzo {}#[tool(description = "Show a task with its comments and image paths.")]- async fn get_task(&self, Parameters(args): Parameters<TaskArgs>) -> Result<CallToolResult, ErrorData> {+ async fn get_task(+ &self,+ Parameters(args): Parameters<TaskArgs>,+ ext: Extensions,+ ) -> Result<CallToolResult, ErrorData> {Ok(self- .run(move |ctx, store| {+ .run_for(&ext, move |ctx, store| {let task = args.id.find(store)?;task_detail(ctx, store, &task)})@@ -390,9 +435,13 @@ impl Kanzo {}#[tool(description = "Add a task, to todo unless you pass status.")]- async fn create_task(&self, Parameters(args): Parameters<CreateTaskArgs>) -> Result<CallToolResult, ErrorData> {+ async fn create_task(+ &self,+ Parameters(args): Parameters<CreateTaskArgs>,+ ext: Extensions,+ ) -> Result<CallToolResult, ErrorData> {Ok(self- .run(move |ctx, store| {+ .run_for(&ext, move |ctx, store| {let project = ctx.project(store, args.project.as_deref())?;let status = args.status.map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty());let description = args.description.as_deref().unwrap_or("");@@ -451,9 +500,13 @@ impl Kanzo {}#[tool(description = "Take the top todo task, move it to doing and show it.")]- async fn next_task(&self, Parameters(args): Parameters<NextTaskArgs>) -> Result<CallToolResult, ErrorData> {+ async fn next_task(+ &self,+ Parameters(args): Parameters<NextTaskArgs>,+ ext: Extensions,+ ) -> Result<CallToolResult, ErrorData> {Ok(self- .run(move |ctx, store| {+ .run_for(&ext, move |ctx, store| {let all = args.project.as_deref().is_some_and(|p| p.trim().eq_ignore_ascii_case("all"));let project = if all { None } else { Some(ctx.project(store, args.project.as_deref())?) };match store.next_task(project.as_ref().map(|p| p.id))? {@@ -488,6 +541,33 @@ impl Kanzo {// untrimmed one for every request.#[tool_handler(router = self.tool_router)]impl ServerHandler for Kanzo {+ /// On a computer that joined another's board, each call goes to that board, so agents+ /// already running switch boards on their next call when this computer joins or leaves.+ async fn call_tool(+ &self,+ request: CallToolRequestParams,+ context: RequestContext<RoleServer>,+ ) -> Result<CallToolResponse, ErrorData> {+ // Over HTTP, the board itself sends calls on when it joined another.+ if let Some(cwd) = &self.ctx.cwd+ && let Net::Joined(host) = Net::load(&self.ctx.home)+ {+ let mut upstream = self.ctx.host.lock().await;+ if upstream.as_ref().is_none_or(|u| u.host() != host) {+ *upstream = Some(share::Upstream::new(host, cwd, &self.ctx.repos));+ }+ let client = context.peer.peer_info().and_then(|p| serde_json::to_value(&*p).ok());+ let upstream = upstream.as_mut().expect("set above");+ let outcome = upstream.call(client, &request.name, request.arguments).await;+ return Ok(match outcome {+ Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]),+ Err(text) => CallToolResult::error(vec![ContentBlock::text(text)]),+ }+ .into());+ }+ self.tool_router.call(ToolCallContext::new(self, request, context)).await+ }+fn get_info(&self) -> ServerConfig {ServerConfig::new(ServerCapabilities::builder().enable_tools().build()).with_server_info(Implementation::new("kanzo", env!("CARGO_PKG_VERSION")))diff --git a/src/share.rs b/src/share.rsindex 0ce903a..3905517 100644--- a/src/share.rs+++ b/src/share.rs@@ -2,11 +2,12 @@//!//! A shared board listens on the network as well as on this computer. A computer that//! joined one keeps its own board as a window onto it: the board hands the page's-//! requests to the host (`forward`).+//! requests to the host (`forward`), and `kanzo mcp` hands it agents' tool calls (`Upstream`).use std::fmt::Write as _;use std::io;use std::net::{IpAddr, SocketAddr};+use std::path::Path;use std::sync::OnceLock;use std::time::Duration;@@ -17,7 +18,7 @@ use axum::extract::Request;use axum::http::{HeaderName, HeaderValue, StatusCode};use axum::response::{IntoResponse, Response};use serde::{Deserialize, Serialize};-use serde_json::{Value, json};+use serde_json::{Map, Value, json};use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};use tokio::net::TcpStream;use tokio_util::io::ReaderStream;@@ -28,7 +29,11 @@ use crate::home::{DEFAULT_PORT, Home};/// `share`, or `join <host:port>`; none for neither. `kanzo sync` leaves it out.pub const FILE: &str = "network";-/// Sent by a guest's board, so the host can list who's using it.+/// Sent by `kanzo mcp` on a guest with every message, so the host finds the agent's+/// project as it would on its own computer.+pub const FOLDER_HEADER: &str = "x-kanzo-folder";+pub const REPOS_HEADER: &str = "x-kanzo-repos";+/// Sent by a guest's board and `kanzo mcp`, so the host can list who's using it.pub const COMPUTER_HEADER: &str = "x-kanzo-computer";/// Larger than any image the board takes.@@ -251,6 +256,12 @@ struct Reply {body: BufReader<TcpStream>,}+impl Reply {+ fn header(&self, name: &str) -> Option<&str> {+ self.headers.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str())+ }+}+async fn send(host: &str, method: &str, path: &str, headers: &[(&str, &str)], body: &[u8]) -> io::Result<Reply> {let connect = tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(host));let mut conn = connect.await.map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;@@ -330,6 +341,93 @@ pub async fn forward(host: &str, req: Request) -> Response {res}+/// `kanzo mcp`'s session with the board this computer joined, for one agent: its tool+/// calls go there, with the agent's folder so the host finds the project.+pub struct Upstream {+ host: String,+ session: Option<String>,+ folder: String,+ repos: String,+}++impl Upstream {+ pub fn new(host: String, folder: &Path, repos: &[String]) -> Self {+ let folder = folder.display().to_string();+ Self { host, session: None, folder, repos: repos.join(",") }+ }++ pub fn host(&self) -> &str {+ &self.host+ }++ /// Calls the tool `name` on the host, as the agent `client` (its `initialize`+ /// parameters, so comments keep its name). Answers its text, or its error.+ pub async fn call(+ &mut self,+ client: Option<Value>,+ name: &str,+ args: Option<Map<String, Value>>,+ ) -> Result<String, String> {+ let init = json!({ "jsonrpc": "2.0", "id": 0, "method": "initialize", "params": client }).to_string();+ let initialized = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;+ let call =+ json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": name, "arguments": args } });+ let call = call.to_string();+ // A host that restarted forgot the session: open a new one, once.+ let mut reply = Err(io::ErrorKind::NotConnected.into());+ for _ in 0..2 {+ if self.session.is_none() {+ self.post(&init).await.map_err(|_| unreachable(&self.host))?;+ let _ = self.post(initialized).await;+ }+ reply = self.post(&call).await;+ match reply {+ Ok((404, _)) => self.session = None,+ _ => break,+ }+ }+ let (status, messages) = reply.map_err(|_| unreachable(&self.host))?;+ let Some(answer) = messages.into_iter().find(|m| m["id"] == 1) else {+ return Err(format!("The shared board answered {status}."));+ };+ if let Some(error) = answer["error"]["message"].as_str() {+ return Err(error.to_string());+ }+ let result = &answer["result"];+ let text =+ result["content"].as_array().into_iter().flatten().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>();+ let text = text.join("\n");+ if result["isError"] == true { Err(text) } else { Ok(text) }+ }++ /// Sends one message: the status, and the messages the host answered with, as JSON+ /// or as a stream of events.+ async fn post(&mut self, line: &str) -> io::Result<(u16, Vec<Value>)> {+ let mut headers = vec![+ ("content-type", "application/json"),+ ("accept", "application/json, text/event-stream"),+ (FOLDER_HEADER, self.folder.as_str()),+ (REPOS_HEADER, self.repos.as_str()),+ (COMPUTER_HEADER, computer()),+ ];+ if let Some(id) = &self.session {+ headers.push(("mcp-session-id", id));+ }+ let mut reply = send(&self.host, "POST", "/mcp", &headers, line.as_bytes()).await?;+ if let Some(id) = reply.header("mcp-session-id") {+ self.session = Some(id.to_string());+ }+ let mut body = String::new();+ reply.body.read_to_string(&mut body).await?;+ let messages = if body.trim_start().starts_with('{') {+ serde_json::from_str(&body).into_iter().collect()+ } else {+ body.lines().filter_map(|l| serde_json::from_str(l.strip_prefix("data:")?.trim()).ok()).collect()+ };+ Ok((reply.status, messages))+ }+}+#[cfg(test)]mod tests {use super::*;