git clone https://garage44.eu/jeroen/midas.git.. /src/mcp.rs
//! `midas mcp`: the workspace's tools for an agent, as an MCP server on stdio
//! (DESIGN.md §8). Claude Code starts it (`claude mcp add midas -- midas mcp`)
//! in the session's own directory, which is what makes "my node" mean the
//! worktree's node here exactly as it does for the `midas` command.
//!
//! Three families:
//!
//! * **Nodes**: status, the event log, a node's story, take and release.
//! * **Sessions**: who else works in the workspace, notes to them, and this
//! session's own notes (collab.rs).
//! * **Forgejo**: repositories, branches, pull requests, workflow dispatch and
//! runs, issues, and a raw API call for anything not listed.
//!
//! **Access is the caller's token.** With a hub key (`~/.config/midas/hub.env`)
//! every Forgejo call goes through the hub, which holds the token for that key
//! (`/srv/midas/callers.json`) and logs the call under the caller's name.
//! Without one, the session's own token is used: `MIDAS_FORGEJO_TOKEN` and
//! `MIDAS_FORGEJO_API`, from the environment or `hub.env`. Either way Forgejo's
//! answer is the access decision; midas adds no permissions. The repository a
//! call is about defaults to `MIDAS_REPO`.
//!
//! HTTPS goes through curl, as the hub's LFS fetches do: midas stays a static
//! binary with no TLS stack, and the token reaches curl on stdin, never argv.
use std::io::{BufRead, Write};
use std::process::{Command, Stdio};
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use crate::events;
use crate::registry;
/// The MCP revision midas speaks: as a server here, and to bots (bot.rs, host.rs).
pub const PROTOCOL: &str = "2025-06-18";
pub fn serve() -> Result<i32> {
let stdin = std::io::stdin();
let mut out = std::io::stdout();
for line in stdin.lock().lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let Ok(msg) = serde_json::from_str::<Value>(&line) else {
reply(&mut out, &json!({"jsonrpc": "2.0", "id": null,
"error": {"code": -32700, "message": "not JSON"}}))?;
continue;
};
let Some(id) = msg.get("id").cloned() else { continue }; // a notification
let method = msg["method"].as_str().unwrap_or("");
let resp = match method {
"initialize" => json!({"jsonrpc": "2.0", "id": id, "result": {
"protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or(PROTOCOL),
"capabilities": {"tools": {}},
"serverInfo": {"name": "midas", "version": env!("CARGO_PKG_VERSION")},
"instructions": "midas: build nodes and Forgejo. Node tools act for the worktree this \
session runs in. Forgejo tools act with this session's own token, so Forgejo's \
answer (including a 403) is the access decision.",
}}),
"ping" => json!({"jsonrpc": "2.0", "id": id, "result": {}}),
"tools/list" => {
// The hub's remote MCP servers' tools (remote.rs) beside midas's own.
let mut all = tools();
all.extend(crate::remote::session_tools());
json!({"jsonrpc": "2.0", "id": id, "result": {"tools": all}})
}
"tools/call" => {
let name = msg["params"]["name"].as_str().unwrap_or("").to_string();
let args = msg["params"]["arguments"].clone();
// A remote's tool: forwarded by the hub, its answer as the remote gave it.
if let Some(r) = crate::remote::call_from_session(&name, &args) {
let result = r.unwrap_or_else(|e| json!({"content": [{"type": "text", "text": format!("{e:#}")}], "isError": true}));
events::emit("mcp_call", json!({"tool": name, "error": result["isError"] == true,
"actor": std::env::current_dir().ok().and_then(|d| d.file_name().map(|n| n.to_string_lossy().to_string()))}));
reply(&mut out, &json!({"jsonrpc": "2.0", "id": id, "result": result}))?;
continue;
}
let (args, unknown) = normalize(&name, args);
let (text, is_error) = match call(&name, &args) {
Ok(t) => (t, false),
Err(e) => (format!("{e:#}{}", takes(&name, &unknown)), true),
};
events::emit("mcp_call", json!({
"tool": name, "error": is_error,
"actor": std::env::current_dir().ok()
.and_then(|d| d.file_name().map(|n| n.to_string_lossy().to_string())),
}));
json!({"jsonrpc": "2.0", "id": id, "result": {
"content": [{"type": "text", "text": text}], "isError": is_error}})
}
_ => json!({"jsonrpc": "2.0", "id": id,
"error": {"code": -32601, "message": format!("no method {method}")}}),
};
reply(&mut out, &resp)?;
}
Ok(0)
}
fn reply(out: &mut impl Write, v: &Value) -> Result<()> {
writeln!(out, "{v}")?;
out.flush()?;
Ok(())
}
/// Arguments under names a tool does not have, moved to the ones it does. An
/// agent often calls a deferred tool before loading its schema and guesses:
/// `{"name": "midas"}` for project_add's `project` failed 76 times in the
/// container's transcripts, `message` for `text` most of the rest. A guessed
/// name is moved when it is a known alias of a missing parameter, or when it
/// is the only unknown one and exactly one required parameter is missing.
/// Returns the arguments and the names still unknown.
fn normalize(name: &str, mut args: Value) -> (Value, Vec<String>) {
const ALIASES: &[(&str, &[&str])] = &[
("text", &["message", "msg", "what", "note", "body", "content", "prompt", "task"]),
("project", &["name", "repo", "project_name"]),
("path", &["file", "file_path", "filepath", "image"]),
("title", &["name"]),
("to", &["session", "target", "recipient"]),
];
let Some(schema) = tools().into_iter().find(|t| t["name"] == name) else {
return (args, vec![]);
};
let Some(obj) = args.as_object_mut() else { return (args, vec![]) };
let props = &schema["inputSchema"]["properties"];
let known = |k: &str| props.get(k).is_some();
for (to, from) in ALIASES {
if known(to) && !obj.contains_key(*to) {
if let Some(k) = from.iter().find(|k| !known(k) && obj.contains_key(**k)) {
let v = obj.remove(*k).unwrap();
obj.insert(to.to_string(), v);
}
}
}
let unknown: Vec<String> = obj.keys().filter(|k| !known(k)).cloned().collect();
let missing: Vec<&str> = schema["inputSchema"]["required"].as_array().into_iter().flatten()
.filter_map(Value::as_str).filter(|k| !obj.contains_key(*k)).collect();
if let ([u], [m]) = (unknown.as_slice(), missing.as_slice()) {
let v = obj.remove(u).unwrap();
obj.insert(m.to_string(), v);
return (args, vec![]);
}
(args, unknown)
}
/// For a failed call: the parameters the tool takes, when it was given others.
fn takes(name: &str, unknown: &[String]) -> String {
let Some(schema) = tools().into_iter().find(|t| t["name"] == name) else { return String::new() };
if unknown.is_empty() {
return String::new();
}
let required: Vec<&str> = schema["inputSchema"]["required"].as_array().into_iter().flatten()
.filter_map(Value::as_str).collect();
let params: Vec<String> = schema["inputSchema"]["properties"].as_object().into_iter().flatten()
.map(|(k, _)| if required.contains(&k.as_str()) { format!("{k} (required)") } else { k.clone() })
.collect();
format!("\n{name} takes: {}; it was given {}, which it does not have.", params.join(", "), unknown.join(", "))
}
fn tool(name: &str, description: &str, props: Value, required: &[&str]) -> Value {
json!({"name": name, "description": description,
"inputSchema": {"type": "object", "properties": props, "required": required}})
}
fn tools() -> Vec<Value> {
let repo = json!({"type": "string", "description": "owner/name; defaults to MIDAS_REPO"});
let s = |d: &str| json!({"type": "string", "description": d});
let n = |d: &str| json!({"type": "integer", "description": d});
vec![
tool("nodes_status", "Who holds each build node, for what, since and until when, what is running, who is queued, and recent events.", json!({}), &[]),
tool("nodes_log", "Query the workspace's event log (claims, refusals, lapsed leases, ssh sessions, guard actions, flushes).",
json!({"since": s("90s, 30m, 2h or 3d (default 2h)"), "kind": s("comma-separated event kinds"),
"node": s("only this node"), "actor": s("substring of the session or job")}), &[]),
tool("node_explain", "The story of one node: who held it, what ran, what waited, what failed.",
json!({"node": s("the node's name"), "since": s("default 24h")}), &["node"]),
tool("node_take", "Claim a node for this session's worktree and sync it; with wait_minutes, wait in the queue for one. Remote nodes are then used with plain `ssh <node> '…'`.",
json!({"machine": s("any, gpu, or a machine's name (default any)"), "node": s("a specific node id"),
"purpose": s("what it is for, shown in nodes_status"),
"wait_minutes": n("wait in line up to this long (max 60) instead of failing at once")}), &[]),
tool("node_release", "Give back the node this session's worktree holds.", json!({}), &[]),
tool("who", "The agent sessions seen lately in the workspace: each one's name (what `say` takes), label, branch, the node it holds or waits for, the files it changes and whose it shares, its unread notes, and when it was last seen. This session's row is marked.",
json!({"all": json!({"type": "boolean", "description": "every session of the last month, ended ones too"})}), &[]),
tool("say", "Leave a note for another session (a name from `who`) or a role: @<node> its holder, @waiting:<machine or node> those in line, @file:<path> whoever changes it. It reaches them at their next prompt or tool call. With `re`, answer the sender of that note instead (its id, e.g. n12).",
json!({"to": s("the session or role; not with re"), "text": s("what to say"), "re": s("a note's id, to answer its sender")}), &["text"]),
tool("notes", "This session's notes from other sessions and the hub, shown now and left unread (the session's own hooks hand them over, so a subagent reading them takes nothing from it); with sent, the notes this session sent in the last two days and whether each was read.",
json!({"sent": json!({"type": "boolean"})}), &[]),
tool("show", "Show the person following this session on the Midas hub page a picture, a sound or a video (png, jpg, gif, webp, svg, mp3, wav, ogg, flac, m4a, mp4, webm, mov; up to 100 MB): it appears in the conversation, playable there. Only in a session started from the page.",
json!({"path": s("the file, absolute or relative to the worktree"), "caption": s("one line under it"),
"tech": s("a picture of a research-tree tech as it really works (its id, k20): kept on its card, where it had a sketch")}), &["path"]),
tool("session_title", "Rename this session on the Midas hub page and the board, when what it is about has changed from what its title says (it was named from its first message). A few words, as a person would name the task. Only in a session started from the page.",
json!({"title": s("the new name, a few words")}), &["title"]),
tool("session_later", "Carry on later: at the time, midas tells this session what it was to do (starting it again if it had ended), and the Midas hub page shows the time meanwhile, with Now, Move and Cancel for the person. Call it whenever you promise work for later (\"the rest tomorrow\", \"after the quota resets\"): without it nothing wakes the session. One time per session; setting it again moves it. Only in a session started from the page.",
json!({"in": s("how long from now: 90m, 4h, 1d, 1d12h"), "at": s("or when: a date, a clock time and its offset from UTC, 2026-10-30T09:00+01:00"),
"text": s("what to do then, in words this session will read"), "cancel": json!({"type": "boolean", "description": "drop the time set instead"})}), &[]),
tool("session_await", "Wait on the person for something only they can do before this session can go on: paste a token, add a DNS record, register an OAuth app. The Midas hub page lists the session under Needs you, with what it waits for, the steps and, for a secret, a field whose value goes straight to where it is used (never to you), until they give it, put it off or decline; midas then tells this session. Call it instead of ending a turn on a request in prose, and before landing without finishing for such a step. One per session; setting it again replaces it. With done, it waits on nothing any more (the person gave it in a reply). Only in a session started from the page.",
json!({"text": s("what you wait for, in a line: Paste an API token for example.org"), "steps": s("the steps to it, as short Markdown (a numbered list, with links)"),
"secret": s("when it is a secret, where it goes: remote:<name> (a remote MCP server's token) or bot:<node or group>:<NAME>"),
"url": s("for remote:<name> the hub does not have yet: its MCP endpoint, https://…/mcp"),
"done": json!({"type": "boolean", "description": "it waits on nothing any more"})}), &[]),
tool("project_add", "Work in one more of the workspace's projects in this session: a worktree of it, on this session's branch off its main, at ./<name> in the session's folder, its skills linked there. Call it when the task needs a project's code (to read, change or build it), once per project; a question needing no code needs none. Only in a session started from the page.",
json!({"project": s("the project, by name (podium) or owner/name")}), &["project"]),
tool("devices", "The devices paired to the hub (an app on the person's phone): online or not, and the tools each offers. A session opened after a device was paired has its tools as an MCP server of their own; this and device_call are for one paired since.", json!({}), &[]),
tool("device_call", "Call one tool of a paired device (see devices), relayed through the hub while its app is open. Pictures are saved and shown to the person.",
json!({"device": s("the device's id, from devices"), "tool": s("the tool's name"), "arguments": json!({"type": "object"})}), &["device", "tool"]),
tool("project_create", "Make a new project, its git repository hosted by the hub (no Forgejo, nobody's hand needed): a first commit on main, its landing gate, a URL to clone. Then project_add brings it into this session. Private unless public is true; turning a private project public later is the person's.",
json!({"name": s("the project's name: letters, digits, - and _"), "description": s("what it is, one line"),
"public": json!({"type": "boolean", "description": "readable by anyone without a login"}),
"gate": s("its landing gate: a command run on a build node in the checkout; unset, it cannot land until set"),
"gate_nodes": s("which nodes may gate it: any (default), gpu, or a machine")}), &["name"]),
tool("project_set", "Change a project the hub hosts: its gate, gate nodes, pre-land check or description (an empty string unsets). public: false makes it private; true is the person's to do.",
json!({"repo": s("owner/name"), "gate": s(""), "gate_nodes": s(""), "pre_land": s(""), "description": s(""),
"public": json!({"type": "boolean"})}), &["repo"]),
tool("project_rename", "Give a project the hub hosts another name (a project renamed during its work, as flits to flitz): its repository, landing, sessions, goals and notes move to it, and the old name still clones and pushes, so checkouts need nothing. Runners move their checkouts; worktrees keep their folder's name. Deleting a project is the person's: they do it on the page (Map ▸ project ▸ Settings ▸ Delete), so ask them (session_await) rather than making a second one beside it.",
json!({"repo": s("owner/name"), "to": s("the new name (or owner/name)")}), &["repo", "to"]),
tool("project_read", "Read a project the hub hosts without a checkout: a file or directory (what: show, with path and rev), its last commits (log), its branches, or one commit with its diff (commit, rev = sha).",
json!({"repo": s("owner/name"), "what": s("show, log, branches or commit"), "path": s("for show"), "rev": s("a branch, tag or sha")}), &["repo", "what"]),
tool("workspace_check","Is the workspace healthy? The hub, registry permissions, every node's heartbeat, disk, build-directory size and warmth, this container's ssh config, Forgejo through the hub, and the last day's failures.", json!({}), &[]),
tool("node_readings", "Each node's latest heartbeat: memory used against its limit, OOM kills, free disk, load, the GPU's shared memory pool, what its checkout is at and warm for, and how long ago it reported.",
json!({"node": s("only this node")}), &[]),
tool("node_drain", "Take a node out of the pool on purpose, with a reason (a current lease runs on; nobody new gets it, the warmer included). Stays drained until node_undrain.",
json!({"node": s("node id"), "why": s("shown in status and the log")}), &["node", "why"]),
tool("node_undrain", "Put a drained node back in the pool.", json!({"node": s("node id")}), &["node"]),
tool("forgejo_repo_create", "Create a repository (under the token's user, or an organisation the token may create in).",
json!({"name": s("repository name"), "owner": s("organisation; omit for the token's own user"),
"private": json!({"type": "boolean"}), "description": s("")}), &["name"]),
tool("forgejo_branches", "List a repository's branches.", json!({"repo": repo}), &[]),
tool("forgejo_pulls", "List pull requests.", json!({"repo": repo, "state": s("open, closed or all (default open)")}), &[]),
tool("forgejo_pull_open", "Open a pull request.",
json!({"repo": repo, "head": s("source branch"), "base": s("default main"), "title": s(""), "body": s("")}),
&["head", "title"]),
tool("forgejo_pull_update", "Change a pull request's title, body or state (open/closed).",
json!({"repo": repo, "number": n("PR number"), "title": s(""), "body": s(""), "state": s("open or closed")}),
&["number"]),
tool("forgejo_pull_merge", "Merge a pull request. Retries while Forgejo is still computing mergeability (its 405).",
json!({"repo": repo, "number": n("PR number"),
"method": s("merge, rebase, rebase-merge, squash or fast-forward-only (default merge)")}),
&["number"]),
tool("forgejo_workflow_dispatch", "Start a workflow_dispatch workflow.",
json!({"repo": repo, "workflow": s("file name, e.g. deploy-web.yml"), "ref": s("default main"),
"inputs": json!({"type": "object", "description": "workflow inputs"})}),
&["workflow"]),
tool("forgejo_runs", "Recent Actions runs (tasks): workflow, status, branch, sha, when.",
json!({"repo": repo, "limit": n("default 10")}), &[]),
tool("forgejo_issues", "List issues.",
json!({"repo": repo, "state": s("open, closed or all"), "labels": s("comma-separated")}), &[]),
tool("forgejo_issue_create", "Open an issue.",
json!({"repo": repo, "title": s(""), "body": s("")}), &["title"]),
tool("forgejo_issue_comment", "Comment on an issue or pull request.",
json!({"repo": repo, "number": n(""), "body": s("")}), &["number", "body"]),
tool("forgejo_api", "Any Forgejo API call, for what the tools above do not cover. Path is relative to /api/v1. A repository's settings, deploy keys and branch protections need its admin, and organisations a read:organization scope; an agent's token usually has neither, so a 403 there means asking the person, not retrying.",
json!({"method": s("GET, POST, PATCH, PUT or DELETE"), "path": s("e.g. /repos/owner/name/tags"),
"body": json!({"type": "object"})}),
&["method", "path"]),
]
}
fn arg<'a>(a: &'a Value, k: &str) -> Option<&'a str> {
a.get(k).and_then(|v| v.as_str()).filter(|s| !s.is_empty())
}
fn call(name: &str, a: &Value) -> Result<String> {
match name {
"nodes_status" => run_self(&["status"]),
// A failing check exits non-zero, which is a finding, not a tool error.
"show" => crate::sessions::show(arg(a, "path").context("path is required")?, arg(a, "caption"), arg(a, "tech")),
"session_title" => crate::sessions::rename_self(arg(a, "title").context("title is required")?),
"session_later" => crate::sessions::later_self(arg(a, "at"), arg(a, "in"), arg(a, "text"), a["cancel"] == true),
"session_await" => crate::sessions::await_self(arg(a, "text"), arg(a, "steps"), arg(a, "secret"), arg(a, "url"), a["done"] == true),
// `name` too: the tool's text said ./<name> and the CLI's argument is
// <name>, so 73 sessions called it so before they saw the schema.
"project_add" => crate::sessions::add_project(arg(a, "project").or_else(|| arg(a, "name")).context("project is required")?),
"devices" => {
let v = crate::client::get("/v1/devices")?;
Ok(serde_json::to_string_pretty(&v["devices"])?)
}
"device_call" => {
let args = a.get("arguments").cloned().unwrap_or(json!({}));
let timeout = crate::device::tool_time(&args);
let r = crate::device::call_from_session(arg(a, "device").context("device is required")?, arg(a, "tool").context("tool is required")?, &args, timeout)?;
Ok(r["content"].as_array().into_iter().flatten().map(|c| match c["type"].as_str() {
Some("text") => c["text"].as_str().unwrap_or("").to_string(),
Some(t) => format!("[{t}]"),
None => String::new(),
}).collect::<Vec<_>>().join("\n"))
}
"project_create" => {
let mut b = json!({"owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(),
"name": arg(a, "name").context("name is required")?, "public": a.get("public").and_then(Value::as_bool) == Some(true)});
for k in ["description", "gate", "gate_nodes"] {
if let Some(v) = arg(a, k) {
b[k] = json!(v);
}
}
crate::client::post("/v1/projects/create", &b).map(|v| v.to_string())
}
"project_set" => {
let mut b = json!({"owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(), "repo": arg(a, "repo").context("repo is required")?});
for k in ["gate", "gate_nodes", "pre_land", "description"] {
if let Some(v) = a.get(k).and_then(Value::as_str) {
b[k] = json!(v);
}
}
if let Some(p) = a.get("public").and_then(Value::as_bool) {
b["public"] = json!(p);
}
crate::client::post("/v1/projects/set", &b).map(|v| v.to_string())
}
"project_rename" => crate::client::post("/v1/projects/rename", &json!({
"owner": crate::client::setting("MIDAS_OWNER").unwrap_or_default(),
"repo": arg(a, "repo").context("repo is required")?, "to": arg(a, "to").context("to is required")?,
})).map(|v| v.to_string()),
"project_read" => {
let repo = crate::mirror::repo_name(arg(a, "repo").context("repo is required")?)?;
let what = arg(a, "what").unwrap_or("show");
let enc = crate::hub::pct_encode;
let mut q = vec![];
if let Some(p) = arg(a, "path") {
q.push(format!("path={}", enc(p)));
}
if let Some(r) = arg(a, "rev") {
q.push(format!("rev={}", enc(r)));
}
crate::client::get(&format!("/v1/repos/{}/{what}?{}", repo.trim_end_matches(".git"), q.join("&")))
.map(|v| v["text"].as_str().map(str::to_string).unwrap_or_else(|| serde_json::to_string_pretty(&v).unwrap_or_default()))
}
"workspace_check" => Ok(String::from_utf8_lossy(&Command::new(crate::util::exe()?).arg("check").output()?.stdout).to_string()),
"nodes_log" => {
let mut v = vec!["log".to_string(), "--since".into(), arg(a, "since").unwrap_or("2h").into()];
for (k, f) in [("kind", "--kind"), ("node", "--node"), ("actor", "--actor")] {
if let Some(x) = arg(a, k) {
v.push(f.into());
v.push(x.into());
}
}
run_self(&v.iter().map(String::as_str).collect::<Vec<_>>())
}
"node_explain" => run_self(&["explain", arg(a, "node").context("node is required")?,
"--since", arg(a, "since").unwrap_or("24h")]),
"node_take" => {
// Waiting is in line, not a poll race: the hub's queue gives the node
// to whoever has waited longest.
let secs = a.get("wait_minutes").and_then(Value::as_u64).map(|m| (m.min(60) * 60).to_string());
let mut v: Vec<&str> = match &secs { Some(s) => vec!["take", "--wait", s], None => vec!["take", "--wait", "0"] };
v.push(arg(a, "machine").unwrap_or("any"));
if let Some(s) = arg(a, "node") {
v.extend(["--node", s]);
}
if let Some(p) = arg(a, "purpose") {
v.extend(["--purpose", p]);
}
run_self(&v)
}
"node_readings" => {
let nodes = crate::client::nodes()?;
Ok(nodes.iter().filter(|n| arg(a, "node").is_none_or(|s| n["id"] == s)).map(|n| {
let id = n["id"].as_str().unwrap_or("?");
match n.get("reading").filter(|r| !r.is_null()) {
Some(r) => format!("{id}: {}\n {}", registry::describe_reading(r), r),
None => format!("{id}: no reading yet"),
}
}).collect::<Vec<_>>().join("\n"))
}
"node_drain" => run_self(&["drain", arg(a, "node").context("node is required")?,
"--why", arg(a, "why").context("why is required")?]),
"node_undrain" => run_self(&["undrain", arg(a, "node").context("node is required")?]),
"node_release" => run_self(&["release"]),
"who" => run_self(if a.get("all").and_then(Value::as_bool) == Some(true) { &["who", "--all"] } else { &["who"] }),
"say" => {
let text = arg(a, "text").context("text is required")?;
// `to: "--re n12"` is the command line's way of saying `re`.
let re = arg(a, "re").or_else(|| arg(a, "to").and_then(|t| t.strip_prefix("--re")).map(str::trim));
match re.filter(|r| !r.is_empty()) {
Some(re) => run_self(&["say", "--re", re, "--", text]),
None => run_self(&["say", "--", arg(a, "to").context("to is required (or re)")?, text]),
}
}
"notes" => run_self(if a.get("sent").and_then(Value::as_bool) == Some(true) { &["notes", "--sent"] } else { &["notes"] }),
"forgejo_repo_create" => {
let mut body = json!({"name": arg(a, "name").context("name is required")?,
"private": a.get("private").and_then(Value::as_bool).unwrap_or(false)});
if let Some(d) = arg(a, "description") {
body["description"] = json!(d);
}
let path = match arg(a, "owner") {
Some(o) => format!("/orgs/{o}/repos"),
None => "/user/repos".into(),
};
forgejo("POST", &path, Some(&body))
}
"forgejo_branches" => forgejo("GET", &format!("/repos/{}/branches?limit=50", repo(a)?), None).map(|t| {
summarise(&t, |b| format!("{} {}", b["name"].as_str().unwrap_or("?"),
b["commit"]["id"].as_str().unwrap_or("").get(..10).unwrap_or("")))
}),
"forgejo_pulls" => forgejo("GET", &format!("/repos/{}/pulls?state={}&limit=50", repo(a)?,
arg(a, "state").unwrap_or("open")), None).map(|t| {
summarise(&t, |p| format!("#{} [{}] {} ({} → {})", p["number"], p["state"].as_str().unwrap_or("?"),
p["title"].as_str().unwrap_or(""), p["head"]["ref"].as_str().unwrap_or("?"),
p["base"]["ref"].as_str().unwrap_or("?")))
}),
"forgejo_pull_open" => forgejo("POST", &format!("/repos/{}/pulls", repo(a)?), Some(&json!({
"head": arg(a, "head").context("head is required")?, "base": arg(a, "base").unwrap_or("main"),
"title": arg(a, "title").context("title is required")?, "body": arg(a, "body").unwrap_or(""),
}))),
"forgejo_pull_update" => {
let mut body = json!({});
for k in ["title", "body", "state"] {
if let Some(v) = arg(a, k) {
body[k] = json!(v);
}
}
forgejo("PATCH", &format!("/repos/{}/pulls/{}", repo(a)?, number(a)?), Some(&body))
}
"forgejo_pull_merge" => {
let path = format!("/repos/{}/pulls/{}/merge", repo(a)?, number(a)?);
let body = json!({"Do": arg(a, "method").unwrap_or("merge")});
// "405 Please try again later" means mergeability is still being computed.
for _ in 0..12 {
match forgejo_raw("POST", &path, Some(&body))? {
(405, t) if t.contains("try again") => std::thread::sleep(std::time::Duration::from_secs(5)),
(c, t) => return finish(c, t),
}
}
bail!("Forgejo was still computing mergeability after a minute; try again")
}
"forgejo_workflow_dispatch" => {
let mut body = json!({"ref": arg(a, "ref").unwrap_or("main")});
if let Some(i) = a.get("inputs").filter(|v| v.is_object()) {
body["inputs"] = i.clone();
}
forgejo("POST", &format!("/repos/{}/actions/workflows/{}/dispatches", repo(a)?,
arg(a, "workflow").context("workflow is required")?), Some(&body))
}
"forgejo_runs" => {
let limit = a.get("limit").and_then(Value::as_u64).unwrap_or(10);
let t = forgejo("GET", &format!("/repos/{}/actions/tasks?limit={limit}", repo(a)?), None)?;
let v: Value = serde_json::from_str(&t).unwrap_or(Value::Null);
let runs = v["workflow_runs"].as_array().cloned().unwrap_or_default();
if runs.is_empty() {
return Ok(t);
}
Ok(runs.iter().map(|r| format!("run {} {} [{}] {} {} {} {}",
r["run_number"], r["name"].as_str().unwrap_or("?"), r["status"].as_str().unwrap_or("?"),
r["event"].as_str().unwrap_or(""), r["head_branch"].as_str().unwrap_or(""),
r["head_sha"].as_str().unwrap_or("").get(..10).unwrap_or(""),
r["updated_at"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("\n"))
}
"forgejo_issues" => {
let mut q = format!("/repos/{}/issues?type=issues&limit=50&state={}", repo(a)?, arg(a, "state").unwrap_or("open"));
if let Some(l) = arg(a, "labels") {
q.push_str(&format!("&labels={l}"));
}
forgejo("GET", &q, None).map(|t| summarise(&t, |i| format!("#{} [{}] {}", i["number"],
i["state"].as_str().unwrap_or("?"), i["title"].as_str().unwrap_or(""))))
}
"forgejo_issue_create" => forgejo("POST", &format!("/repos/{}/issues", repo(a)?), Some(&json!({
"title": arg(a, "title").context("title is required")?, "body": arg(a, "body").unwrap_or("")}))),
"forgejo_issue_comment" => forgejo("POST", &format!("/repos/{}/issues/{}/comments", repo(a)?, number(a)?),
Some(&json!({"body": arg(a, "body").context("body is required")?}))),
"forgejo_api" => {
let method = arg(a, "method").context("method is required")?.to_ascii_uppercase();
let path = arg(a, "path").context("path is required")?;
if !path.starts_with('/') || path.contains("..") {
bail!("path is relative to /api/v1 and starts with /");
}
forgejo(&method, path, a.get("body").filter(|b| !b.is_null()))
}
_ => bail!("no tool {name}"),
}
}
fn run_self(args: &[&str]) -> Result<String> {
let mut c = Command::new(crate::util::exe()?);
c.args(args);
output(c)
}
fn output(mut c: Command) -> Result<String> {
let out = c.stdin(Stdio::null()).output().context("running a node command")?;
let mut text = String::from_utf8_lossy(&out.stdout).to_string();
let err = String::from_utf8_lossy(&out.stderr);
if !err.trim().is_empty() {
text.push_str(&format!("\n[stderr]\n{}", err.trim()));
}
if !out.status.success() {
bail!("{}", text.trim());
}
Ok(text.trim().to_string())
}
fn number(a: &Value) -> Result<u64> {
a.get("number").and_then(|v| v.as_u64().or_else(|| v.as_str().and_then(|s| s.parse().ok())))
.context("number is required")
}
struct Forgejo {
api: String,
token: String,
}
fn forgejo_cfg() -> Result<Forgejo> {
let get = crate::client::setting;
let token = get("MIDAS_FORGEJO_TOKEN")
.context("no Forgejo access: give this machine a hub key (hub.env), or set MIDAS_FORGEJO_TOKEN")?;
let api = get("MIDAS_FORGEJO_API").context("set MIDAS_FORGEJO_API, e.g. https://git.example/api/v1")?;
Ok(Forgejo { api: api.trim_end_matches('/').into(), token })
}
fn repo(a: &Value) -> Result<String> {
let r = match arg(a, "repo") {
Some(r) => r.to_string(),
None => crate::client::setting("MIDAS_REPO").context("say which repo (owner/name), or set MIDAS_REPO")?,
};
if r.split('/').count() != 2 || r.contains("..") {
bail!("repo is owner/name, not {r:?}");
}
Ok(r)
}
fn finish(code: u16, text: String) -> Result<String> {
if (200..300).contains(&code) {
Ok(if text.trim().is_empty() { format!("HTTP {code}") } else { text })
} else {
bail!("Forgejo answered HTTP {code}: {}", text.chars().take(2000).collect::<String>())
}
}
fn forgejo(method: &str, path: &str, body: Option<&Value>) -> Result<String> {
let (c, t) = forgejo_raw(method, path, body)?;
finish(c, t)
}
fn forgejo_raw(method: &str, path: &str, body: Option<&Value>) -> Result<(u16, String)> {
// Through the hub when this session has a hub key: the hub holds the Forgejo
// token for this caller, so the session needs none (DESIGN.md §8).
if let Some((hub_url, key)) = hub_caller() {
let body = body.map(|b| b.to_string());
let (code, text) = crate::hub::request_auth(&hub_url, method, &format!("/v1/forgejo{path}"), body.as_deref(), Some(&key))
.context("asking the hub")?;
if code == 401 {
bail!("the hub refused this session's key (~/.config/midas/hub.env)");
}
return Ok((code, text));
}
let f = forgejo_cfg()?;
curl_forgejo(&f.api, &f.token, method, path, body.map(|b| b.to_string()).as_deref())
}
/// `MIDAS_HUB` and `MIDAS_HUB_KEY`, from the environment or ~/.config/midas/hub.env.
fn hub_caller() -> Option<(String, String)> {
Some((crate::client::hub_url(), crate::client::key()?))
}
/// One Forgejo API call through curl. The token and the body go to curl as a
/// config on stdin, so neither shows in the process list. Shared with the hub's
/// proxy, which calls it with the token it holds for the caller.
pub fn curl_forgejo(api: &str, token: &str, method: &str, path: &str, body: Option<&str>) -> Result<(u16, String)> {
// The body is the caller's, byte for byte, when the hub proxies it.
let quote = crate::util::curl_quote;
let mut cfg = format!(
"silent\nshow-error\nlocation\nrequest = {}\nurl = {}\nheader = {}\nheader = \"Accept: application/json\"\nwrite-out = \"\\n%{{http_code}}\"\n",
quote(method), quote(&format!("{}{}", api.trim_end_matches('/'), path)), quote(&format!("Authorization: token {token}")));
if let Some(b) = body {
cfg.push_str("header = \"Content-Type: application/json\"\n");
cfg.push_str(&format!("data-binary = {}\n", quote(b)));
}
let mut child = Command::new("curl").args(["-K", "-", "--max-time", "60"])
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.spawn().context("starting curl")?;
child.stdin.take().unwrap().write_all(cfg.as_bytes())?;
let out = child.wait_with_output()?;
let text = String::from_utf8_lossy(&out.stdout).to_string();
let (body, code) = text.rsplit_once('\n').unwrap_or(("", text.as_str()));
let code: u16 = code.trim().parse().unwrap_or(0);
if code == 0 {
bail!("curl failed: {}", String::from_utf8_lossy(&out.stderr).trim());
}
Ok((code, body.to_string()))
}
/// A list response, one line per item, so a tool result reads like a listing
/// rather than a page of JSON. Anything that is not a JSON array is returned as is.
fn summarise(text: &str, line: impl Fn(&Value) -> String) -> String {
match serde_json::from_str::<Value>(text) {
Ok(Value::Array(items)) if items.is_empty() => "(none)".into(),
Ok(Value::Array(items)) => items.iter().map(line).collect::<Vec<_>>().join("\n"),
_ => text.to_string(),
}
}
/// Forgejo's version, through whichever route this session uses — `midas
/// check`'s proof that the route works.
pub fn forgejo_version() -> Result<String> {
let t = forgejo("GET", "/version", None)?;
Ok(serde_json::from_str::<Value>(&t).ok().and_then(|v| v["version"].as_str().map(str::to_string)).unwrap_or(t))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guessed_argument_names_reach_the_parameter() {
let (a, u) = normalize("project_add", json!({"name": "midas"}));
assert_eq!((a, u.len()), (json!({"project": "midas"}), 0));
let (a, _) = normalize("say", json!({"to": "s1", "message": "hi"}));
assert_eq!(a, json!({"to": "s1", "text": "hi"}));
let (a, _) = normalize("session_later", json!({"in": "3h", "what": "check"}));
assert_eq!(a, json!({"in": "3h", "text": "check"}));
// A tool's own parameter is never renamed, and an unknown guess is said.
let (a, _) = normalize("forgejo_repo_create", json!({"name": "x"}));
assert_eq!(a, json!({"name": "x"}));
let (_, u) = normalize("session_later", json!({"in": "3h", "when": "x", "why": "y"}));
assert_eq!(u.len(), 2);
assert!(takes("session_later", &u).contains("in, at, text, cancel") || takes("session_later", &u).contains("text"));
}
}