Skip to main content

trumly_mcp/
main.rs

1//! `trumly-mcp [--write] DIR`: a Model Context Protocol server over a model folder, so an agent can read the
2//! design graph, query it and check it. With `--write` it can also change the model (the working copy: the person
3//! reviews with `git diff` and publishes with a commit). Speaks JSON-RPC 2.0, one message per line, on stdin/stdout.
4//!
5//! The folder is re-read on every call: the files are the source of truth and may change underneath us.
6
7use std::io::{self, BufRead, Write};
8use std::path::Path;
9use std::process::Command;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use serde_json::{json, Map, Value};
13use trumly_core::format::node_to_markdown;
14use trumly_core::ops::{id_problem, rename_node};
15use trumly_core::parse::{node_from_map, parse_node};
16use trumly_core::report::{check, node_to_json, Report};
17use trumly_fs::{apply_edit, portable_id, read_model, rev_of_text, write_atomically};
18
19/// The tools that only read. Always on.
20fn read_tools() -> Vec<Value> {
21    vec![
22        json!({"name": "get_index",
23         "description": "A markdown map of the whole model: counts, planes in order, the group tree, every node (id and title) by plane and type, rules and what is failing. Read this first, then open only the nodes you need with get_node.",
24         "inputSchema": {"type": "object", "properties": {}}}),
25        json!({"name": "get_node",
26         "description": "One node in full (frontmatter and markdown body), plus its inbound links, rule results, and `rev`, the revision you must pass back as `base_rev` to change it.",
27         "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]}}),
28        json!({"name": "list_nodes",
29         "description": "List nodes (id, type, title, plane, parent), optionally filtered by type, plane or ancestor.",
30         "inputSchema": {"type": "object", "properties": {
31             "type": {"type": "string"}, "plane": {"type": "string"}, "under": {"type": "string", "description": "only descendants of this node id"}}}}),
32        json!({"name": "search",
33         "description": "Find nodes whose id, title, fields or body contain some text (case-insensitive). Returns where it matched and a snippet. Use it when you do not know the id.",
34         "inputSchema": {"type": "object", "properties": {
35             "query": {"type": "string"}, "type": {"type": "string", "description": "only nodes of this type"}, "limit": {"type": "integer", "description": "at most this many (default 20, max 100)"}}, "required": ["query"]}}),
36        json!({"name": "get_links",
37         "description": "The links of one node in both directions: where it points (with the target's title, and whether the target exists) and what points at it.",
38         "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]}}),
39        json!({"name": "check",
40         "description": "Validate the model and run its rules. Returns counts, structural findings, failed rule results and ghosts (links that should exist).",
41         "inputSchema": {"type": "object", "properties": {}}}),
42        json!({"name": "status",
43         "description": "What has changed since the last commit (needs git), and what this server has changed in this session. Look at it before you hand work back.",
44         "inputSchema": {"type": "object", "properties": {}}}),
45    ]
46}
47
48/// The tools that change the model. Offered only when the server was started with `--write`.
49fn write_tools() -> Vec<Value> {
50    vec![
51        json!({"name": "put_node",
52         "description": "Create a node, or replace one. Pass `node` in the shape get_node returns (id, type, title, parent, plane, fields, links, body). To replace an existing node you must pass its current `rev` as `base_rev`; if the node changed since you read it you get a conflict, so read it again and redo your change. Returns the new rev and the check findings for the node, so fix anything it reports.",
53         "inputSchema": {"type": "object", "properties": {"node": {"type": "object"}, "base_rev": {"type": "string"}}, "required": ["node"]}}),
54        json!({"name": "delete_node",
55         "description": "Delete a node. Pass its current `rev` as `base_rev`. Returns the links that now point at nothing.",
56         "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}, "base_rev": {"type": "string"}}, "required": ["id", "base_rev"]}}),
57        json!({"name": "rename_node",
58         "description": "Give a node a new id. Every link, parent and rule filter that used the old id follows.",
59         "inputSchema": {"type": "object", "properties": {"from": {"type": "string"}, "to": {"type": "string"}}, "required": ["from", "to"]}}),
60    ]
61}
62
63fn tools(write: bool) -> Value {
64    let mut all = read_tools();
65    if write {
66        all.extend(write_tools());
67    }
68    Value::Array(all)
69}
70
71fn instructions(write: bool) -> String {
72    format!(
73        "A trumly design model: a typed graph of markdown nodes. Call get_index first, then open only the nodes you need with get_node. Use search when you do not know an id. {}",
74        if write {
75            "This server can change the model (put_node, delete_node, rename_node). Changes are made in the working copy, not committed: the person reviews and publishes them. Read a node before you change it and pass its rev back as base_rev. Every change returns the check findings, so fix what it reports."
76        } else {
77            "This server is read-only."
78        }
79    )
80}
81
82fn is_under<'a>(report: &'a Report, mut id: &'a str, ancestor: &str) -> bool {
83    let mut hops = 0;
84    while let Some(parent) = report.graph.get(id).and_then(|n| n.parent.as_deref()) {
85        if parent == ancestor {
86            return true;
87        }
88        id = parent;
89        hops += 1;
90        if hops > report.graph.len() {
91            break; // a parent cycle; stop rather than loop forever
92        }
93    }
94    false
95}
96
97/// Where one server run is pointed, and what it has done.
98struct Server {
99    dir: String,
100    write: bool,
101    /// Changes made by this run, oldest first, so `status` can say what the agent did.
102    session: Vec<Value>,
103}
104
105/// The file text of node `id`, with its path.
106fn file_of<'a>(files: &'a [(String, String)], id: &str) -> Option<&'a (String, String)> {
107    files.iter().find(|(_, text)| parse_node(text).is_ok_and(|n| n.id == id))
108}
109
110fn now() -> u64 {
111    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
112}
113
114/// How the model stands after a change: whole-model totals, and what the checks say about one node.
115fn standing(dir: &str, id: Option<&str>) -> Result<Value, String> {
116    let report = check(read_model(dir)?);
117    let j = report.to_json();
118    let failed: Vec<&Value> = j["results"].as_array().unwrap().iter().filter(|r| r["status"] == "fail").collect();
119    let about = |list: &Value| -> Vec<Value> {
120        list.as_array().map(|a| a.iter().filter(|f| id.is_some_and(|i| f["node"] == i || f["ref"] == i)).cloned().collect()).unwrap_or_default()
121    };
122    let mut out = json!({
123        "model": {"ok": report.exit_code() == 0, "errors": j["structure"]["errors"].as_array().map_or(0, Vec::len), "failed_rules": failed.len()},
124    });
125    if id.is_some() {
126        out["findings"] = json!({
127            "errors": about(&j["structure"]["errors"]),
128            "warnings": about(&j["structure"]["warnings"]),
129            "failed_rules": failed.iter().filter(|r| id.is_some_and(|i| r["node"] == i)).collect::<Vec<_>>(),
130        });
131    }
132    Ok(out)
133}
134
135fn contains_ci(hay: &str, needle_lc: &str) -> Option<usize> {
136    let lc = hay.to_lowercase();
137    lc.find(needle_lc).map(|b| lc[..b].chars().count())
138}
139
140fn snippet(text: &str, at: usize, len: usize) -> String {
141    let chars: Vec<char> = text.chars().collect();
142    let from = at.saturating_sub(40).min(chars.len());
143    let to = (at + len + 60).min(chars.len());
144    let mut s: String = chars[from..to].iter().collect::<String>().replace('\n', " ");
145    if from > 0 {
146        s.insert(0, '…');
147    }
148    if to < chars.len() {
149        s.push('…');
150    }
151    s
152}
153
154fn git(dir: &str, args: &[&str]) -> Option<String> {
155    let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?;
156    out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
157}
158
159impl Server {
160    fn need_write(&self) -> Result<(), String> {
161        if self.write { Ok(()) } else { Err("this server is read-only: it was started without --write".into()) }
162    }
163
164    fn call_tool(&mut self, name: &str, args: &Value) -> Result<Value, String> {
165        let dir = self.dir.clone();
166        let dir = dir.as_str();
167        let files = read_model(dir)?;
168        let report = check(files.clone());
169        match name {
170            "check" => {
171                let j = report.to_json();
172                let failed: Vec<&Value> = j["results"].as_array().unwrap().iter().filter(|r| r["status"] == "fail").collect();
173                Ok(json!({
174                    "nodes": report.graph.len(),
175                    "load_errors": j["load_errors"],
176                    "structure": j["structure"],
177                    "failed_rules": failed,
178                    "ghosts": j["ghosts"],
179                    "ok": report.exit_code() == 0,
180                }))
181            }
182            "get_index" => Ok(json!(report.index())),
183            "get_node" => {
184                let id = args["id"].as_str().ok_or("get_node needs an 'id'")?;
185                let node = report.graph.get(id).ok_or(format!("no node with id '{id}'"))?;
186                let inbound: Vec<Value> = report
187                    .graph
188                    .nodes()
189                    .flat_map(|o| o.links.iter().filter(|l| l.to == id).map(move |l| json!({"from": o.id, "type": l.kind})))
190                    .collect();
191                let results: Vec<Value> = report
192                    .evaluation
193                    .results
194                    .iter()
195                    .filter(|r| r.node == id)
196                    .map(|r| json!({"rule": r.rule, "severity": r.severity, "status": r.status.as_str()}))
197                    .collect();
198                let (path, rev) = file_of(&files, id).map(|(p, t)| (json!(p), json!(rev_of_text(t)))).unwrap_or((Value::Null, Value::Null));
199                Ok(json!({"node": node_to_json(node), "path": path, "rev": rev, "inbound": inbound, "rules": results}))
200            }
201            "list_nodes" => {
202                let want = |k: &str| args[k].as_str();
203                let rows: Vec<Value> = report
204                    .graph
205                    .nodes()
206                    .filter(|n| want("type").is_none_or(|t| n.kind.as_deref() == Some(t)))
207                    .filter(|n| want("plane").is_none_or(|p| n.plane.as_deref() == Some(p)))
208                    .filter(|n| want("under").is_none_or(|a| is_under(&report, &n.id, a)))
209                    .map(|n| json!({"id": n.id, "type": n.kind, "title": n.title, "plane": n.plane, "parent": n.parent}))
210                    .collect();
211                Ok(json!(rows))
212            }
213            "search" => {
214                let query = args["query"].as_str().ok_or("search needs a 'query'")?.trim().to_lowercase();
215                if query.is_empty() {
216                    return Err("search needs a non-empty 'query'".into());
217                }
218                let limit = args["limit"].as_u64().unwrap_or(20).clamp(1, 100) as usize;
219                let mut rows = Vec::new();
220                let mut total = 0;
221                for n in report.graph.nodes().filter(|n| args["type"].as_str().is_none_or(|t| n.kind.as_deref() == Some(t))) {
222                    let mut matched = Vec::new();
223                    let mut snip = None;
224                    if n.id.to_lowercase().contains(&query) {
225                        matched.push("id");
226                    }
227                    if n.title.to_lowercase().contains(&query) {
228                        matched.push("title");
229                    }
230                    let fields = serde_json::to_string(&n.fields).unwrap_or_default();
231                    if let Some(at) = contains_ci(&fields, &query) {
232                        matched.push("fields");
233                        snip.get_or_insert_with(|| snippet(&fields, at, query.chars().count()));
234                    }
235                    if let Some(at) = contains_ci(&n.body, &query) {
236                        matched.push("body");
237                        snip.get_or_insert_with(|| snippet(&n.body, at, query.chars().count()));
238                    }
239                    if matched.is_empty() {
240                        continue;
241                    }
242                    total += 1;
243                    if rows.len() < limit {
244                        rows.push(json!({"id": n.id, "type": n.kind, "title": n.title, "matched": matched, "snippet": snip}));
245                    }
246                }
247                Ok(json!({"total": total, "shown": rows.len(), "results": rows}))
248            }
249            "get_links" => {
250                let id = args["id"].as_str().ok_or("get_links needs an 'id'")?;
251                let node = report.graph.get(id).ok_or(format!("no node with id '{id}'"))?;
252                let outbound: Vec<Value> = node
253                    .links
254                    .iter()
255                    .map(|l| {
256                        let target = report.graph.get(&l.to);
257                        json!({"type": l.kind, "to": l.to, "key": l.key, "fields": l.fields, "to_title": target.map(|t| t.title.clone()), "exists": target.is_some()})
258                    })
259                    .collect();
260                let inbound: Vec<Value> = report
261                    .graph
262                    .nodes()
263                    .flat_map(|o| o.links.iter().filter(|l| l.to == id).map(move |l| json!({"from": o.id, "from_title": o.title, "type": l.kind, "key": l.key})))
264                    .collect();
265                Ok(json!({"id": id, "outbound": outbound, "inbound": inbound}))
266            }
267            "status" => {
268                let tracked = git(dir, &["diff", "--name-status", "--relative", "HEAD", "--", "."]);
269                let fresh = git(dir, &["ls-files", "--others", "--exclude-standard"]);
270                let changed = match (&tracked, &fresh) {
271                    (None, None) => Value::Null,
272                    _ => {
273                        let mut rows: Vec<Value> = Vec::new();
274                        let mut add = |status: &str, path: &str| {
275                            if path.ends_with(".md") {
276                                let node_id = files.iter().find(|(p, _)| p == path).and_then(|(_, t)| parse_node(t).ok()).map(|n| n.id).or_else(|| Path::new(path).file_stem().map(|s| s.to_string_lossy().into_owned()));
277                                rows.push(json!({"path": path, "status": status, "id": node_id}));
278                            }
279                        };
280                        for line in tracked.iter().flat_map(|t| t.lines()) {
281                            if let Some((st, path)) = line.split_once('\t') {
282                                add(match st.chars().next() { Some('A') => "added", Some('D') => "deleted", _ => "modified" }, path.rsplit('\t').next().unwrap_or(path));
283                            }
284                        }
285                        for path in fresh.iter().flat_map(|t| t.lines()) {
286                            add("added", path);
287                        }
288                        Value::Array(rows)
289                    }
290                };
291                Ok(json!({"git": changed != Value::Null, "since_last_commit": changed, "this_session": self.session}))
292            }
293            "put_node" => {
294                self.need_write()?;
295                let mut fm: Map<String, Value> = args["node"].as_object().cloned().ok_or("put_node needs a 'node' object")?;
296                let body = match fm.remove("body") {
297                    Some(Value::String(b)) => b,
298                    None | Some(Value::Null) => String::new(),
299                    Some(_) => return Err("the node's body must be text".into()),
300                };
301                let node = node_from_map(&fm, body).map_err(|e| format!("invalid node: {}", e.as_str()))?;
302                let base_rev = args["base_rev"].as_str();
303                let existing = file_of(&files, &node.id);
304                let rel = match existing {
305                    Some((rel, text)) => {
306                        let current = rev_of_text(text);
307                        if base_rev != Some(current.as_str()) {
308                            return Err(format!("conflict: '{}' is not at the revision you read (it is now {current}). Read it again with get_node, then redo your change on top of it.", node.id));
309                        }
310                        rel.clone()
311                    }
312                    None => {
313                        if base_rev.is_some() {
314                            return Err(format!("conflict: '{}' no longer exists (it was deleted after you read it). Create it again without base_rev if you mean to.", node.id));
315                        }
316                        let namespaced = node.kind.as_deref() == Some("pack") || node.fields.get("pack").is_some_and(Value::is_string);
317                        if !portable_id(&node.id, namespaced) {
318                            return Err("new ids use lower-case letters, digits, '-' or '_' (max 100), start and end with a letter or digit, and have no '--' unless the node belongs to a pack. That keeps the file name working on every system.".into());
319                        }
320                        if let Some(problem) = id_problem(&report.graph, "", &node.id) {
321                            return Err(problem);
322                        }
323                        format!("{}.md", node.id)
324                    }
325                };
326                let text = node_to_markdown(&node);
327                let path = Path::new(dir).join(&rel);
328                if let Some(parent) = path.parent() {
329                    std::fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
330                }
331                write_atomically(&path, &text).map_err(|e| format!("write failed: {e}"))?;
332                self.session.push(json!({"tool": "put_node", "id": node.id, "at": now(), "created": existing.is_none()}));
333                let mut out = standing(dir, Some(&node.id))?;
334                out["id"] = json!(node.id);
335                out["path"] = json!(rel);
336                out["rev"] = json!(rev_of_text(&text));
337                out["created"] = json!(existing.is_none());
338                Ok(out)
339            }
340            "delete_node" => {
341                self.need_write()?;
342                let id = args["id"].as_str().ok_or("delete_node needs an 'id'")?;
343                let (rel, text) = file_of(&files, id).ok_or(format!("no node with id '{id}'"))?;
344                if args["base_rev"].as_str() != Some(rev_of_text(text).as_str()) {
345                    return Err(format!("conflict: '{id}' is not at the revision you read. Read it again with get_node first."));
346                }
347                std::fs::remove_file(Path::new(dir).join(rel)).map_err(|e| format!("delete failed: {e}"))?;
348                let dangling: Vec<Value> = report.graph.nodes().filter(|o| o.id != id).flat_map(|o| o.links.iter().filter(|l| l.to == id).map(move |l| json!({"from": o.id, "type": l.kind}))).collect();
349                self.session.push(json!({"tool": "delete_node", "id": id, "at": now()}));
350                let mut out = standing(dir, None)?;
351                out["deleted"] = json!(id);
352                out["dangling_links"] = json!(dangling);
353                Ok(out)
354            }
355            "rename_node" => {
356                self.need_write()?;
357                let from = args["from"].as_str().ok_or("rename_node needs 'from'")?;
358                let to = args["to"].as_str().ok_or("rename_node needs 'to'")?;
359                let edit = rename_node(&report.graph, from, to)?;
360                let (written, removed) = apply_edit(dir, &edit)?;
361                self.session.push(json!({"tool": "rename_node", "id": from, "to": to, "at": now()}));
362                let mut out = standing(dir, Some(to))?;
363                out["renamed"] = json!(edit.renamed);
364                out["rewritten"] = json!(written);
365                out["removed"] = json!(removed);
366                Ok(out)
367            }
368            other => Err(format!("unknown tool '{other}'")),
369        }
370    }
371
372    /// Handle one JSON-RPC message. Returns None for notifications, which get no reply.
373    fn handle(&mut self, msg: &Value) -> Option<Value> {
374        let id = msg.get("id")?.clone(); // no id = a notification
375        let result = match msg["method"].as_str().unwrap_or("") {
376            "initialize" => Ok(json!({
377                "protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or("2025-03-26"),
378                "capabilities": {"tools": {}},
379                "serverInfo": {"name": "trumly", "version": env!("CARGO_PKG_VERSION")},
380                "instructions": instructions(self.write)
381            })),
382            "ping" => Ok(json!({})),
383            "tools/list" => Ok(json!({"tools": tools(self.write)})),
384            "tools/call" => {
385                let p = &msg["params"];
386                // A failing tool is a normal result with isError set, so the model can read and react to it.
387                let (text, is_error) = match self.call_tool(p["name"].as_str().unwrap_or(""), &p["arguments"]) {
388                    Ok(Value::String(t)) => (t, false), // text tools (the index) go out as they are
389                    Ok(v) => (serde_json::to_string_pretty(&v).unwrap(), false),
390                    Err(e) => (e, true),
391                };
392                Ok(json!({"content": [{"type": "text", "text": text}], "isError": is_error}))
393            }
394            other => Err(json!({"code": -32601, "message": format!("method not found: {other}")})),
395        };
396        Some(match result {
397            Ok(r) => json!({"jsonrpc": "2.0", "id": id, "result": r}),
398            Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": e}),
399        })
400    }
401}
402
403fn main() {
404    let mut write = false;
405    let mut dir = None;
406    for a in std::env::args().skip(1) {
407        match a.as_str() {
408            "--write" => write = true,
409            _ => dir = dir.or(Some(a)),
410        }
411    }
412    let mut server = Server { dir: dir.unwrap_or_else(|| ".".to_string()), write, session: Vec::new() };
413    let stdout = io::stdout();
414    for line in io::stdin().lock().lines() {
415        let Ok(line) = line else { break };
416        if line.trim().is_empty() {
417            continue;
418        }
419        let reply = match serde_json::from_str::<Value>(&line) {
420            Ok(msg) => server.handle(&msg),
421            Err(_) => Some(json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "parse error"}})),
422        };
423        if let Some(r) = reply {
424            let mut out = stdout.lock();
425            let _ = writeln!(out, "{r}");
426            let _ = out.flush();
427        }
428    }
429}