diff --git a/Cargo.lock b/Cargo.lock index a68d9a0..d353a8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -670,6 +670,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.19.0" @@ -1973,6 +1979,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -2417,6 +2425,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2695,6 +2709,26 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "regex" version = "1.13.1" @@ -2819,6 +2853,52 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ece64e19631fc38758181e637c15509a2c2709ee53bfde1e1d58f9dc991f919e" +dependencies = [ + "async-trait", + "base64 0.23.1", + "bytes", + "chrono", + "futures", + "http", + "http-body", + "http-body-util", + "indexmap", + "libc", + "pastey", + "pin-project-lite", + "rand 0.10.3", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sse-stream", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", + "tracing", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "967fa7f7935d7d6217d593df0e8e5c9307bcaf256974a5a9ee64476c97735389" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.9", +] + [[package]] name = "rrule" version = "0.14.0" @@ -2995,6 +3075,32 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.9", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -3060,6 +3166,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -3198,6 +3315,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "sse-stream" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -3335,6 +3465,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-mcp" +version = "0.1.0" +dependencies = [ + "chrono", + "http", + "rmcp", + "rusqlite", + "serde", + "serde_json", + "synapse-core", + "synapse-import", + "tempfile", + "tokio", + "uuid", +] + [[package]] name = "synapse-search" version = "0.1.0" @@ -3688,6 +3835,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.20" diff --git a/crates/synapse-mcp/Cargo.toml b/crates/synapse-mcp/Cargo.toml new file mode 100644 index 0000000..0bacbc7 --- /dev/null +++ b/crates/synapse-mcp/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "synapse-mcp" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "MCP (Model Context Protocol) server over a Synapse graph: stdio binary + Streamable HTTP service" + +[lib] +name = "synapse_mcp" + +[[bin]] +name = "synapse-mcp" +path = "src/main.rs" + +[dependencies] +synapse-core.workspace = true +# Logseq-style Markdown outline parser (write tools turn Markdown into nested blocks). +synapse-import = { path = "../synapse-import" } +chrono.workspace = true +serde.workspace = true +serde_json.workspace = true +uuid.workspace = true +rusqlite.workspace = true +# Request parts (the HTTP server passes the graph to tools through their extensions). +http = "1" +# Official MCP SDK: protocol types, tool router/schemas, stdio and Streamable HTTP transports. +rmcp = { version = "3.7", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std"] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/synapse-mcp/src/lib.rs b/crates/synapse-mcp/src/lib.rs new file mode 100644 index 0000000..dc2775d --- /dev/null +++ b/crates/synapse-mcp/src/lib.rs @@ -0,0 +1,552 @@ +//! MCP (Model Context Protocol) server over a Synapse graph. See `docs/mcp.md`. +//! +//! * [`tools`]: the tool implementations, plain functions over a [`Graph`] returning compact +//! Markdown (testable without MCP). +//! * [`SynapseMcp`]: the rmcp handler (tool list/schemas, resources, dispatch). +//! * [`GraphHost`]: how a call reaches the graph. [`LocalHost`] opens a local graph +//! directory per call (stdio binary, next to the running app); the sync server provides +//! its own host over its shared graphs and exposes the handler over Streamable HTTP. +//! +//! Read tools run inside a transaction that is always rolled back, so they can never change +//! the graph. Write tools run in `BEGIN IMMEDIATE` (short write lock, retried while SQLite is +//! busy) through the normal `Graph` API, so every change is logged as ops and syncs. +//! Journals are read-only: write tools refuse journal pages. + +pub mod params; +pub mod text; +pub mod tools; + +use params::*; +use rmcp::handler::server::router::tool::ToolRouter; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{ + CallToolResult, ContentBlock, ListResourceTemplatesResult, PaginatedRequestParams, + ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, ResourceContents, + ResourceTemplate, ServerCapabilities, ServerConfig, +}; +use rmcp::service::RequestContext; +use rmcp::{ErrorData, RoleServer, ServerHandler, tool, tool_handler, tool_router}; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use synapse_core::Graph; +use tools::{ToolError, ToolResult}; + +/// A unit of work on the graph (runs on a blocking thread; may be retried when busy). +pub type Job = Box ToolResult + Send + Sync + 'static>; +pub type HostFuture = Pin + Send + 'static>>; + +/// Gives tool calls access to a graph. +pub trait GraphHost: Send + Sync + 'static { + /// Runs `job` with exclusive use of the graph's connection. + fn run(&self, job: Job) -> HostFuture; +} + +/// The host for this request. The HTTP server puts it in the request extensions (one per +/// graph); stdio sets it on the handler. +#[derive(Clone)] +pub struct HostRef(pub Arc); + +/// A local graph directory, opened per call so this process never keeps state (or an old +/// clock) next to the app that owns the graph. SQLite WAL lets both use it at once. +pub struct LocalHost { + dir: PathBuf, +} + +impl LocalHost { + /// Fails when `dir` holds no graph (never creates one). + pub fn new(dir: impl Into) -> std::io::Result { + let dir = dir.into(); + if !dir.join("synapse.db").is_file() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("no Synapse graph in {} (synapse.db missing)", dir.display()), + )); + } + Ok(Self { dir }) + } +} + +impl GraphHost for LocalHost { + fn run(&self, job: Job) -> HostFuture { + let dir = self.dir.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || { + let g = Graph::open(&dir).map_err(ToolError::from)?; + job(&g) + }) + .await + .map_err(|e| ToolError::new(format!("internal error: {e}")))? + }) + } +} + +/// Rolls back on drop unless committed. +struct Txn<'a> { + g: &'a Graph, + open: bool, +} + +impl<'a> Txn<'a> { + fn begin(g: &'a Graph, sql: &str) -> Result { + g.conn().execute_batch(sql)?; + Ok(Self { g, open: true }) + } + fn commit(mut self) -> Result<(), ToolError> { + self.open = false; + self.g.conn().execute_batch("COMMIT")?; + Ok(()) + } +} + +impl Drop for Txn<'_> { + fn drop(&mut self) { + if self.open { + let _ = self.g.conn().execute_batch("ROLLBACK"); + } + } +} + +const BUSY_RETRIES: usize = 3; + +fn with_retry(g: &Graph, f: impl Fn(&Graph) -> ToolResult) -> ToolResult { + let mut attempt = 0; + loop { + match f(g) { + Err(e) if e.busy && attempt < BUSY_RETRIES => { + attempt += 1; + std::thread::sleep(std::time::Duration::from_millis(200 * attempt as u64)); + } + other => return other, + } + } +} + +/// Wraps a read: a deferred transaction (consistent snapshot) that is always rolled back. +pub fn read_job(f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static) -> Job { + Box::new(move |g| { + with_retry(g, |g| { + let _tx = Txn::begin(g, "BEGIN")?; + f(g) + }) + }) +} + +/// Wraps a write: `BEGIN IMMEDIATE` (takes the write lock up front, waits while busy), +/// committed only when the tool succeeds. +pub fn write_job(f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static) -> Job { + Box::new(move |g| { + with_retry(g, |g| { + let tx = Txn::begin(g, "BEGIN IMMEDIATE")?; + let out = f(g)?; + tx.commit()?; + Ok(out) + }) + }) +} + +const INSTRUCTIONS: &str = "Synapse is an outliner notes graph (Logseq-like): pages made of \ +nested Markdown blocks, daily journals (pages titled YYYY-MM-DD), [[links]], #tags, one optional \ +type per page, and hubs (folders). Pages are addressed by title, alias or id; blocks by the \ +((id)) shown after them. Typical workflow: read recent journals (get_journal, journal_links, \ +timeline), then curate pages: create pages for things mentioned in journals, type and tag them \ +reusing the existing vocabulary (list_types, list_tags) and file them in hubs. Journals are \ +read-only through this server."; + +/// The MCP handler. Cheap to clone. +#[derive(Clone)] +pub struct SynapseMcp { + host: Option>, + allow_write: bool, + tool_router: ToolRouter, +} + +fn reply(r: ToolResult) -> Result { + Ok(match r { + Ok(text) => CallToolResult::success(vec![ContentBlock::text(text)]), + Err(e) => CallToolResult::error(vec![ContentBlock::text(e.message)]), + }) +} + +impl SynapseMcp { + /// `host`: the graph for every call (stdio), or `None` to take it from the HTTP request + /// extensions ([`HostRef`]). Write tools are only listed and callable with `allow_write`. + pub fn new(host: Option>, allow_write: bool) -> Self { + let mut tool_router = Self::read_tools(); + if allow_write { + tool_router.merge(Self::write_tools()); + } + Self { + host, + allow_write, + tool_router, + } + } + + fn host_for(&self, ctx: &RequestContext) -> Result, ToolError> { + if let Some(h) = &self.host { + return Ok(h.clone()); + } + ctx.extensions + .get::() + .and_then(|p| p.extensions.get::()) + .map(|h| h.0.clone()) + .ok_or_else(|| ToolError::new("no graph bound to this request")) + } + + async fn read( + &self, + ctx: &RequestContext, + f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static, + ) -> Result { + reply(match self.host_for(ctx) { + Ok(h) => h.run(read_job(f)).await, + Err(e) => Err(e), + }) + } + + async fn write( + &self, + ctx: &RequestContext, + f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static, + ) -> Result { + if !self.allow_write { + return reply(Err(ToolError::new("this server is read-only"))); + } + reply(match self.host_for(ctx) { + Ok(h) => h.run(write_job(f)).await, + Err(e) => Err(e), + }) + } +} + +#[tool_router(router = read_tools, vis = "")] +impl SynapseMcp { + #[tool( + description = "Full-text search over page titles/aliases and block text (all words must match; case- and accent-insensitive). Returns [[page]] ((block-id)) date: snippet. Filters: scope, journals, tag, type, hub, page, from/to dates.", + annotations(read_only_hint = true) + )] + async fn search( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::search(g, &p)).await + } + + #[tool( + description = "A page (by title, alias, id or journal date) with its type, tags, hub, aliases, properties and its outline as indented Markdown; each block ends with its ((id)). Use `block` for a subtree, `max_depth` to skim, cursor for long pages. Hubs list their members.", + annotations(read_only_hint = true) + )] + async fn get_page( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::get_page(g, &p)).await + } + + #[tool( + description = "Journal outline for a day (YYYY-MM-DD, \"today\", \"yesterday\"; default today) or every journal in a from/to range (max 31 days, oldest first).", + annotations(read_only_hint = true) + )] + async fn get_journal( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::get_journal(g, &p)).await + } + + #[tool( + description = "List pages with filters (type, tag, hub, untyped, untagged, updated_since, created_since, journals exclude/include/only), sorted by updated, created or title, paginated with a cursor.", + annotations(read_only_hint = true) + )] + async fn list_pages( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::list_pages(g, &p)).await + } + + #[tool( + description = "Linked references to a page: the blocks that link it, grouped by source page, with their parent block as context.", + annotations(read_only_hint = true) + )] + async fn backlinks( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::backlinks(g, &p)).await + } + + #[tool( + description = "Pages related to a page by spreading activation over links, co-visits and time (strongest first).", + annotations(read_only_hint = true) + )] + async fn related( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::related(g, &p)).await + } + + #[tool( + description = "Tags in use with page counts. Reuse these names when tagging.", + annotations(read_only_hint = true) + )] + async fn list_tags( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::list_tags(g, &p)).await + } + + #[tool( + description = "Page types in use with counts and icons, then defined/suggested unused ones. Reuse these names when typing pages.", + annotations(read_only_hint = true) + )] + async fn list_types( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::list_types(g, &p)).await + } + + #[tool( + description = "The hub (folder) tree with note counts, or the members of one hub.", + annotations(read_only_hint = true) + )] + async fn hubs( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::hubs(g, &p)).await + } + + #[tool( + description = "Per day between from and to (default last 7 days, max 92): whether a journal exists, pages born that day and pages edited.", + annotations(read_only_hint = true) + )] + async fn timeline( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::timeline(g, &p)).await + } + + #[tool( + description = "Curation helper: per journal day (default last 7 days, max 31), the pages it links with their status (type, tags, hub, untyped, untagged, empty) and existing pages it mentions without linking.", + annotations(read_only_hint = true) + )] + async fn journal_links( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.read(&ctx, move |g| tools::journal_links(g, &p)).await + } +} + +#[tool_router(router = write_tools, vis = "")] +impl SynapseMcp { + #[tool( + description = "Create a page with optional type, tags, hub and a Markdown outline body. `source_journal` records the journal day it comes from. Fails if the title exists.", + annotations(read_only_hint = false, destructive_hint = false) + )] + async fn create_page( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::create_page(g, &p)).await + } + + #[tool( + description = "Append a Markdown outline to a page (at the end, or under a parent block). Journals are read-only.", + annotations(read_only_hint = false, destructive_hint = false) + )] + async fn append_blocks( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::append_blocks(g, &p)).await + } + + #[tool( + description = "Replace the text of a block on a page (children are kept). Journal blocks are read-only.", + annotations(read_only_hint = false, destructive_hint = true) + )] + async fn update_block( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::update_block(g, &p)).await + } + + #[tool( + description = "Delete a block and its children from a page. Journal blocks are read-only.", + annotations(read_only_hint = false, destructive_hint = true) + )] + async fn delete_block( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::delete_block(g, &p)).await + } + + #[tool( + description = "Set (or clear with null) the single type of a page.", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn set_page_type( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::set_page_type(g, &p)).await + } + + #[tool( + description = "Change a page's explicit tags: `tags` replaces them all; `add` / `remove` edit them.", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn set_page_tags( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::set_page_tags(g, &p)).await + } + + #[tool( + description = "Move a page into a hub (a page has at most one), or out of its hub with null.", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn set_page_hub( + &self, + Parameters(p): Parameters, + ctx: RequestContext, + ) -> Result { + self.write(&ctx, move |g| tools::set_page_hub(g, &p)).await + } +} + +#[tool_handler(router = self.tool_router)] +impl ServerHandler for SynapseMcp { + fn get_info(&self) -> ServerConfig { + let mut instructions = INSTRUCTIONS.to_string(); + if !self.allow_write { + instructions.push_str(" This server is read-only."); + } + ServerConfig::new( + ServerCapabilities::builder() + .enable_tools() + .enable_resources() + .build(), + ) + .with_server_info(rmcp::model::Implementation::new( + "synapse-mcp", + env!("CARGO_PKG_VERSION"), + )) + .with_instructions(instructions) + } + + async fn list_resource_templates( + &self, + _request: Option, + _ctx: RequestContext, + ) -> Result { + let t = |uri: &str, name: &str, desc: &str| { + ResourceTemplate::new(uri, name) + .with_description(desc) + .with_mime_type("text/markdown") + }; + Ok(ListResourceTemplatesResult::with_all_items(vec![ + t( + "synapse://page/{title}", + "page", + "A page (title, alias or id) as a Markdown outline", + ), + t( + "synapse://journal/{date}", + "journal", + "A journal day (YYYY-MM-DD or today) as a Markdown outline", + ), + ])) + } + + async fn read_resource( + &self, + request: ReadResourceRequestParams, + ctx: RequestContext, + ) -> Result { + let uri = request.uri.clone(); + let target = if let Some(t) = uri.strip_prefix("synapse://page/") { + percent_decode(t) + } else if let Some(d) = uri.strip_prefix("synapse://journal/") { + percent_decode(d) + } else { + return Err(ErrorData::invalid_params( + format!("unknown resource {uri}"), + None, + )); + }; + let host = self + .host_for(&ctx) + .map_err(|e| ErrorData::internal_error(e.message, None))?; + let text = host + .run(read_job(move |g| tools::page_resource(g, &target))) + .await + .map_err(|e| ErrorData::invalid_params(e.message, None))?; + Ok(ReadResourceResult::new(vec![ + ResourceContents::text(text, uri).with_mime_type("text/markdown"), + ]) + .into()) + } +} + +/// Decodes `%XX` escapes (titles in resource URIs). +fn percent_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && i + 2 < bytes.len() + && let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3]) + .ok() + .and_then(|h| u8::from_str_radix(h, 16).ok()) + { + out.push(b); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} diff --git a/crates/synapse-mcp/src/main.rs b/crates/synapse-mcp/src/main.rs new file mode 100644 index 0000000..963ecdd --- /dev/null +++ b/crates/synapse-mcp/src/main.rs @@ -0,0 +1,80 @@ +//! `synapse-mcp`: MCP server over stdio for a local Synapse graph. +//! +//! Usage: `synapse-mcp [--graph ] [--allow-write]`. The graph defaults to +//! `$SYNAPSE_GRAPH`, else the app's own location (`/graph`). + +use rmcp::ServiceExt; +use std::path::PathBuf; +use std::sync::Arc; +use synapse_mcp::{LocalHost, SynapseMcp}; + +const USAGE: &str = "usage: synapse-mcp [--graph ] [--allow-write] + +MCP server (stdio) for a local Synapse graph. Read-only unless --allow-write. +The graph defaults to $SYNAPSE_GRAPH, else the app's directory: + Linux: $XDG_DATA_HOME/dev.dasemu.synapse/graph (~/.local/share/...) + Windows: %APPDATA%\\dasemu\\Synapse\\graph"; + +/// The directory the Flutter app uses (`getApplicationSupportDirectory()/graph`). +fn default_graph() -> Option { + if let Some(g) = std::env::var_os("SYNAPSE_GRAPH").filter(|v| !v.is_empty()) { + return Some(g.into()); + } + if cfg!(windows) { + let appdata = std::env::var_os("APPDATA")?; + return Some( + PathBuf::from(appdata) + .join("dasemu") + .join("Synapse") + .join("graph"), + ); + } + let data = std::env::var_os("XDG_DATA_HOME") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))?; + Some(data.join("dev.dasemu.synapse").join("graph")) +} + +fn fail(msg: &str) -> ! { + eprintln!("synapse-mcp: {msg}"); + std::process::exit(2); +} + +#[tokio::main] +async fn main() { + let mut graph: Option = None; + let mut allow_write = false; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--graph" => graph = Some(args.next().unwrap_or_else(|| fail(USAGE)).into()), + "--allow-write" => allow_write = true, + "-h" | "--help" => { + println!("{USAGE}"); + return; + } + _ => fail(USAGE), + } + } + let dir = graph + .or_else(default_graph) + .unwrap_or_else(|| fail("no graph directory; pass --graph ")); + let host = LocalHost::new(&dir).unwrap_or_else(|e| fail(&e.to_string())); + eprintln!( + "synapse-mcp: serving {} ({})", + dir.display(), + if allow_write { + "read-write" + } else { + "read-only" + } + ); + let server = SynapseMcp::new(Some(Arc::new(host)), allow_write) + .serve(rmcp::transport::stdio()) + .await + .unwrap_or_else(|e| fail(&format!("startup failed: {e}"))); + if let Err(e) = server.waiting().await { + fail(&format!("server error: {e}")); + } +} diff --git a/crates/synapse-mcp/src/params.rs b/crates/synapse-mcp/src/params.rs new file mode 100644 index 0000000..c5f2a1d --- /dev/null +++ b/crates/synapse-mcp/src/params.rs @@ -0,0 +1,236 @@ +//! Tool parameters. Doc comments become the JSON-schema descriptions the model reads. + +use rmcp::schemars; +use serde::Deserialize; + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct SearchParams { + /// Words to find (all must match, case- and accent-insensitive). Use "double quotes" for + /// an exact phrase. + pub query: String, + /// What to search: "all" (default), "pages" (titles and aliases) or "blocks". + #[serde(default)] + pub scope: Option, + /// Journals: "any" (default), "only" or "exclude". + #[serde(default)] + pub journals: Option, + /// Only pages carrying this tag (explicit, implied by their type or by their hub). + #[serde(default)] + pub tag: Option, + /// Only pages of this type. + #[serde(default, rename = "type")] + pub page_type: Option, + /// Only direct members of this hub (title). + #[serde(default)] + pub hub: Option, + /// Only one page (title, alias, id or journal date). + #[serde(default)] + pub page: Option, + /// From date (YYYY-MM-DD, inclusive): journal date for journals, last edit for the rest. + #[serde(default)] + pub from: Option, + /// To date (YYYY-MM-DD, inclusive). + #[serde(default)] + pub to: Option, + /// Max results (default 20, max 100). + #[serde(default)] + pub limit: Option, + /// Cursor from a previous call ("next cursor"). + #[serde(default)] + pub cursor: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct GetPageParams { + /// Page title, alias, id, or a journal date (YYYY-MM-DD / "today"). + pub page: String, + /// Show only the subtree under this block id. + #[serde(default)] + pub block: Option, + /// Max outline depth to show (0 = top-level blocks only). + #[serde(default)] + pub max_depth: Option, + /// Append each block's own id as a trailing `((id))` (default true; needed to edit blocks). + #[serde(default)] + pub ids: Option, + /// Max blocks per call (default 400). + #[serde(default)] + pub limit: Option, + /// Cursor from a previous call ("next cursor"). + #[serde(default)] + pub cursor: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct GetJournalParams { + /// A day: YYYY-MM-DD, "today" or "yesterday". Default today. Ignored when from/to is set. + #[serde(default)] + pub date: Option, + /// Range start (YYYY-MM-DD). With `to`: every existing journal in the range (max 31 days). + #[serde(default)] + pub from: Option, + /// Range end (YYYY-MM-DD, default today). + #[serde(default)] + pub to: Option, + /// Append block ids as `((id))` (default true). + #[serde(default)] + pub ids: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct ListPagesParams { + /// Only pages of this type. + #[serde(default, rename = "type")] + pub page_type: Option, + /// Only pages with this tag (explicit, from their type or their hub). + #[serde(default)] + pub tag: Option, + /// Only direct members of this hub (title). + #[serde(default)] + pub hub: Option, + /// Only notes without a type (journals and hubs excluded). + #[serde(default)] + pub untyped: Option, + /// Only notes without explicit tags (journals and hubs excluded). + #[serde(default)] + pub untagged: Option, + /// Only pages edited on or after this date (YYYY-MM-DD). + #[serde(default)] + pub updated_since: Option, + /// Only pages created on or after this date (YYYY-MM-DD). + #[serde(default)] + pub created_since: Option, + /// Journals: "exclude" (default), "include" or "only". + #[serde(default)] + pub journals: Option, + /// Sort: "updated" (default, newest first), "created" (newest first) or "title". + #[serde(default)] + pub sort: Option, + /// Max results (default 50, max 200). + #[serde(default)] + pub limit: Option, + /// Cursor from a previous call. + #[serde(default)] + pub cursor: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct PageRefParams { + /// Page title, alias, id or journal date. + pub page: String, + /// Max items (default 50 for backlinks, 15 for related). + #[serde(default)] + pub limit: Option, + /// Cursor from a previous call (backlinks only). + #[serde(default)] + pub cursor: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct ListParams { + /// Max items (default 100). + #[serde(default)] + pub limit: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct HubsParams { + /// Show this hub's members instead of the whole hub tree. + #[serde(default)] + pub hub: Option, + /// In the tree, also list each hub's member notes (default false). + #[serde(default)] + pub members: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct RangeParams { + /// Start date (YYYY-MM-DD, default 7 days before `to`). + #[serde(default)] + pub from: Option, + /// End date (YYYY-MM-DD or "today", default today). + #[serde(default)] + pub to: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct CreatePageParams { + /// Title of the new page (not a date; must not exist yet). + pub title: String, + /// Page type (one per page), e.g. "Book". Reuse names from list_types when possible. + #[serde(default, rename = "type")] + pub page_type: Option, + /// Tags. Reuse names from list_tags when possible. + #[serde(default)] + pub tags: Option>, + /// Hub (title of an existing hub) to file the page under. + #[serde(default)] + pub hub: Option, + /// Body as a Markdown outline ("- " bullets, 2-space indents for children; `key:: value` + /// lines are properties). Plain paragraphs become top-level blocks. + #[serde(default)] + pub content: Option, + /// Journal day (YYYY-MM-DD) the page comes from; it is recorded as the day the page was + /// born. The journal must exist. Default: today. + #[serde(default)] + pub source_journal: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct AppendBlocksParams { + /// Target page (title, alias or id). Journals are read-only. + pub page: String, + /// Markdown outline to append ("- " bullets, 2-space indents for children). + pub content: String, + /// Append as children of this block id (default: at the end of the page). + #[serde(default)] + pub parent: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct UpdateBlockParams { + /// Block id. + pub block: String, + /// New Markdown content of the block (replaces the old text; children are kept). + pub content: String, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct DeleteBlockParams { + /// Block id (its children are deleted too). + pub block: String, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct SetPageTypeParams { + /// Page title, alias or id. + pub page: String, + /// New type, or null / "" to clear it. + #[serde(default, rename = "type")] + pub page_type: Option, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct SetPageTagsParams { + /// Page title, alias or id. + pub page: String, + /// Replace all explicit tags with this list (omit to keep them and use add/remove). + #[serde(default)] + pub tags: Option>, + /// Tags to add. + #[serde(default)] + pub add: Option>, + /// Tags to remove. + #[serde(default)] + pub remove: Option>, +} + +#[derive(Debug, Default, Deserialize, schemars::JsonSchema)] +pub struct SetPageHubParams { + /// Page title, alias or id. + pub page: String, + /// Hub title to move the page into (a page has at most one hub), or null to remove it + /// from its hub. + #[serde(default)] + pub hub: Option, +} diff --git a/crates/synapse-mcp/src/text.rs b/crates/synapse-mcp/src/text.rs new file mode 100644 index 0000000..3e1b9b6 --- /dev/null +++ b/crates/synapse-mcp/src/text.rs @@ -0,0 +1,133 @@ +//! Small text helpers: accent/case folding for matching, truncation and snippets. + +/// Lowercases and strips common Latin diacritics so "Canción" matches "cancion". Keeps a +/// one-to-one char mapping (needed to map match offsets back onto the original text). +pub fn fold_char(c: char) -> char { + let c = c.to_lowercase().next().unwrap_or(c); + match c { + 'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a', + 'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ė' | 'ę' | 'ě' => 'e', + 'í' | 'ì' | 'î' | 'ï' | 'ī' | 'į' => 'i', + 'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ő' => 'o', + 'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ů' | 'ű' | 'ų' => 'u', + 'ý' | 'ÿ' => 'y', + 'ñ' | 'ń' | 'ň' => 'n', + 'ç' | 'ć' | 'č' => 'c', + 'ś' | 'š' | 'ş' => 's', + 'ź' | 'ż' | 'ž' => 'z', + 'ł' => 'l', + 'ř' => 'r', + 'ď' => 'd', + 'ť' => 't', + 'ğ' => 'g', + _ => c, + } +} + +pub fn fold(s: &str) -> String { + s.chars().map(fold_char).collect() +} + +/// First `max` chars of `s` (with "…" when cut), on one line. +pub fn truncate(s: &str, max: usize) -> String { + let flat = one_line(s); + match flat.char_indices().nth(max) { + Some((i, _)) => format!("{}…", &flat[..i]), + None => flat, + } +} + +/// Collapses newlines and runs of whitespace into single spaces. +pub fn one_line(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +/// A window of about `width` chars of `text` around the first occurrence of any folded +/// `term`, on one line. +pub fn snippet(text: &str, terms: &[String], width: usize) -> String { + let flat = one_line(text); + let chars: Vec = flat.chars().collect(); + if chars.len() <= width { + return flat; + } + let folded: Vec = chars.iter().map(|c| fold_char(*c)).collect(); + let hay: String = folded.iter().collect(); + let first = terms + .iter() + .filter_map(|t| hay.find(t.as_str())) + .min() + .map(|byte| hay[..byte].chars().count()) + .unwrap_or(0); + let start = first.saturating_sub(width / 3); + let end = (start + width).min(chars.len()); + let start = end.saturating_sub(width); + let mut out = String::new(); + if start > 0 { + out.push('…'); + } + out.extend(&chars[start..end]); + if end < chars.len() { + out.push('…'); + } + out +} + +/// Number of non-overlapping occurrences of `needle` in `hay`. +pub fn count(hay: &str, needle: &str) -> usize { + if needle.is_empty() { + return 0; + } + hay.matches(needle).count() +} + +/// Whether `needle` occurs in `hay` delimited by non-alphanumeric chars on both sides. +pub fn contains_word(hay: &str, needle: &str) -> bool { + hay.match_indices(needle).any(|(i, m)| { + let before = hay[..i].chars().next_back(); + let after = hay[i + m.len()..].chars().next(); + !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric) + }) +} + +/// Splits a query into folded terms; `"quoted phrases"` stay together. +pub fn query_terms(query: &str) -> Vec { + let mut out = Vec::new(); + for (i, part) in query.split('"').enumerate() { + if i % 2 == 1 { + let p = fold(&one_line(part)); + if !p.is_empty() { + out.push(p); + } + } else { + out.extend(part.split_whitespace().map(fold)); + } + } + out.retain(|t| !t.is_empty()); + out.dedup(); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn folding_and_terms() { + assert_eq!(fold("Canción ÑANDÚ"), "cancion nandu"); + assert_eq!( + query_terms(r#"foo "Bar Baz" qux"#), + vec!["foo", "bar baz", "qux"] + ); + assert!(contains_word("hola rust!", "rust")); + assert!(!contains_word("trusty", "rust")); + assert_eq!(truncate("a\nb c", 3), "a b…"); + } + + #[test] + fn snippet_centres_on_match() { + let text = format!("{} needle {}", "x".repeat(200), "y".repeat(200)); + let s = snippet(&text, &["needle".into()], 40); + assert!(s.contains("needle"), "{s}"); + assert!(s.starts_with('…') && s.ends_with('…')); + } +} diff --git a/crates/synapse-mcp/src/tools.rs b/crates/synapse-mcp/src/tools.rs new file mode 100644 index 0000000..37827f8 --- /dev/null +++ b/crates/synapse-mcp/src/tools.rs @@ -0,0 +1,1333 @@ +//! Tool implementations: plain functions over a [`Graph`] returning compact Markdown. +//! +//! They only use the public `synapse_core` API (plus read-only queries on the core `pages`, +//! `blocks` and `aliases` tables for full-text scans). Journals are read-only: every write +//! refuses journal pages. + +use crate::params::*; +use crate::text::{contains_word, count, fold, one_line, query_terms, snippet, truncate}; +use chrono::{Duration, Local, NaiveDate, TimeZone}; +use std::collections::{HashMap, HashSet}; +use std::fmt::Write as _; +use synapse_core::parse::extract_refs; +use synapse_core::{Block, BlockId, Graph, Page, PageId, Placement, journal_title, title_key}; +use uuid::Uuid; + +/// Error shown to the model as the tool result (never a protocol error). +#[derive(Debug, Clone, PartialEq)] +pub struct ToolError { + pub message: String, + /// SQLite was busy (another process holds the write lock); the call may be retried. + pub busy: bool, +} + +impl ToolError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + busy: false, + } + } +} + +impl std::fmt::Display for ToolError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl From for ToolError { + fn from(e: synapse_core::Error) -> Self { + use synapse_core::Error as E; + match e { + E::NotFound(m) => Self::new(format!("not found: {m}")), + E::Invalid(m) => Self::new(m), + E::Conflict(m) => Self::new(m), + E::Sqlite(e) => Self::from(e), + other => Self::new(format!("storage error: {other}")), + } + } +} + +impl From for ToolError { + fn from(e: rusqlite::Error) -> Self { + let busy = matches!( + e.sqlite_error_code(), + Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked) + ); + Self { + message: if busy { + "the graph is busy (another process is writing); try again".into() + } else { + format!("storage error: {e}") + }, + busy, + } + } +} + +pub type ToolResult = Result; + +const MAX_RANGE_DAYS: i64 = 31; +const MAX_TIMELINE_DAYS: i64 = 92; + +// ------------------------------------------------------------------ helpers + +fn err(m: impl Into) -> ToolError { + ToolError::new(m) +} + +fn day_of_ms(ms: i64) -> NaiveDate { + Local + .timestamp_millis_opt(ms) + .earliest() + .map(|d| d.date_naive()) + .unwrap_or_default() +} + +fn fmt_day(ms: i64) -> String { + journal_title(day_of_ms(ms)) +} + +/// `YYYY-MM-DD`, `today`, `yesterday` or `tomorrow`. +pub fn parse_date(g: &Graph, s: &str) -> Result { + let s = s.trim().trim_start_matches("[[").trim_end_matches("]]"); + let today = g.today(); + match s.to_ascii_lowercase().as_str() { + "today" => Ok(today), + "yesterday" => Ok(today - Duration::days(1)), + "tomorrow" => Ok(today + Duration::days(1)), + _ => NaiveDate::parse_from_str(s, "%Y-%m-%d") + .map_err(|_| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))), + } +} + +fn opt_date(g: &Graph, s: &Option) -> Result, ToolError> { + s.as_deref() + .filter(|s| !s.trim().is_empty()) + .map(|s| parse_date(g, s)) + .transpose() +} + +/// `[from, to]` with defaults (`to` = today, `from` = `to` - `default_days`), capped. +fn date_range( + g: &Graph, + from: &Option, + to: &Option, + default_days: i64, + max_days: i64, +) -> Result<(NaiveDate, NaiveDate), ToolError> { + let to = opt_date(g, to)?.unwrap_or_else(|| g.today()); + let from = opt_date(g, from)?.unwrap_or(to - Duration::days(default_days)); + if from > to { + return Err(err("`from` is after `to`")); + } + if (to - from).num_days() >= max_days { + return Err(err(format!("range too long: at most {max_days} days"))); + } + Ok((from, to)) +} + +fn parse_cursor(c: &Option) -> Result { + match c.as_deref().map(str::trim).filter(|c| !c.is_empty()) { + None => Ok(0), + Some(c) => c.parse().map_err(|_| err(format!("bad cursor {c:?}"))), + } +} + +fn limit(l: Option, default: u32, max: u32) -> usize { + l.unwrap_or(default).clamp(1, max) as usize +} + +fn parse_block_id(s: &str) -> Result { + let s = s + .trim() + .trim_start_matches("((") + .trim_end_matches("))") + .trim(); + Uuid::parse_str(s).map_err(|_| err(format!("bad block id {s:?}"))) +} + +fn get_block(g: &Graph, s: &str) -> Result { + let id = parse_block_id(s)?; + g.get_block(id)? + .ok_or_else(|| err(format!("block {id} not found"))) +} + +/// A page by title, alias, id, `[[Title]]` or journal date. +pub fn resolve_page(g: &Graph, s: &str) -> Result { + let s = s.trim(); + let s = s + .strip_prefix("[[") + .and_then(|x| x.strip_suffix("]]")) + .unwrap_or(s) + .trim(); + if s.is_empty() { + return Err(err("empty page name")); + } + if let Ok(id) = Uuid::parse_str(s) + && let Some(p) = g.get_page(id)? + { + return Ok(p); + } + if let Some(p) = g.page_by_title(s)? { + return Ok(p); + } + if let Ok(d) = parse_date(g, s) { + return g + .get_page(synapse_core::store::journal_id(d))? + .ok_or_else(|| err(format!("no journal for {}", journal_title(d)))); + } + let q = fold(s); + let mut close: Vec = g + .all_titles()? + .into_iter() + .map(|(t, _)| t) + .filter(|t| fold(t).contains(&q)) + .collect(); + close.sort_by_key(|t| t.chars().count()); + close.dedup(); + close.truncate(5); + Err(err(if close.is_empty() { + format!("page {s:?} not found") + } else { + format!( + "page {s:?} not found; did you mean: {}?", + close + .iter() + .map(|t| format!("[[{t}]]")) + .collect::>() + .join(", ") + ) + })) +} + +fn resolve_hub(g: &Graph, s: &str) -> Result { + let p = resolve_page(g, s)?; + if !p.is_hub() { + return Err(err(format!( + "[[{}]] is not a hub (see the `hubs` tool)", + p.title + ))); + } + Ok(p) +} + +/// A page the write tools may change: never a journal (journals are read-only over MCP). +fn writable_page(g: &Graph, s: &str) -> Result { + let p = resolve_page(g, s)?; + ensure_writable(&p)?; + Ok(p) +} + +fn ensure_writable(p: &Page) -> Result<(), ToolError> { + if p.is_journal() { + return Err(err(format!( + "journal {} is read-only here; write to a page instead", + p.title + ))); + } + if p.is_template() { + return Err(err("hub templates cannot be edited here")); + } + Ok(()) +} + +fn hub_title(g: &Graph, p: &Page) -> Result, ToolError> { + match p.hubs.first() { + Some(h) => Ok(g.get_page(*h)?.filter(Page::is_hub).map(|h| h.title)), + None => Ok(None), + } +} + +/// `type: X · tags: a, b · hub: H` (only the parts present). +fn page_facets(g: &Graph, p: &Page) -> Result, ToolError> { + let mut parts = Vec::new(); + if p.is_hub() { + parts.push("hub page".to_string()); + } + if let Some(t) = p.page_type() { + parts.push(format!("type: {t}")); + } + if !p.tags.is_empty() { + parts.push(format!("tags: {}", p.tags.join(", "))); + } + if let Some(h) = hub_title(g, p)? { + parts.push(format!("hub: {h}")); + } + Ok(parts) +} + +fn props_inline(props: &synapse_core::Properties) -> String { + props + .iter() + .map(|(k, v)| match v.as_str() { + Some(s) => format!("{k}: {}", truncate(s, 120)), + None => format!("{k}: {}", truncate(&v.to_string(), 120)), + }) + .collect::>() + .join("; ") +} + +/// One outline block as indented Markdown (continuation lines and `key:: value` properties +/// indented under the bullet). +fn render_block(out: &mut String, depth: usize, b: &Block, ids: bool) { + let pad = " ".repeat(depth); + let mut lines = b.content.lines(); + let first = lines.next().unwrap_or(""); + let _ = write!(out, "{pad}- {first}"); + if ids { + let _ = write!(out, " (({}))", b.id); + } + out.push('\n'); + for l in lines { + let _ = writeln!(out, "{pad} {l}"); + } + for (k, v) in &b.properties { + let v = v + .as_str() + .map(str::to_string) + .unwrap_or_else(|| v.to_string()); + let _ = writeln!(out, "{pad} {k}:: {v}"); + } +} + +fn page_block_count(g: &Graph, page: PageId) -> Result { + Ok(g.conn().query_row( + "SELECT count(*) FROM blocks WHERE page_id=?1", + [page.to_string()], + |r| r.get(0), + )?) +} + +// -------------------------------------------------------------------- reads + +/// `get_page`: header (type, tags, hub, aliases, properties, dates) + outline. +pub fn get_page(g: &Graph, p: &GetPageParams) -> ToolResult { + let page = resolve_page(g, &p.page)?; + let ids = p.ids.unwrap_or(true); + let mut out = format!("# {}\n", page.title); + let _ = writeln!(out, "- id: {}", page.id); + for f in page_facets(g, &page)? { + let _ = writeln!(out, "- {f}"); + } + let aliases = g.aliases_of(page.id)?; + if !aliases.is_empty() { + let _ = writeln!(out, "- aliases: {}", aliases.join(", ")); + } + if !page.properties.is_empty() { + let _ = writeln!(out, "- properties: {}", props_inline(&page.properties)); + } + if !page.is_journal() { + let mut dates = format!( + "- created: {} · updated: {}", + fmt_day(page.created_at), + fmt_day(page.updated_at) + ); + if let Some(o) = page.origin_journal { + let _ = write!(dates, " · born in [[{}]]", journal_title(o)); + } + let _ = writeln!(out, "{dates}"); + } + if page.is_hub() { + if !page.description.is_empty() { + let _ = writeln!(out, "\n{}", page.description); + } + let members = g.hub_members(page.id)?; + let _ = writeln!(out, "\n## Members ({})", members.len()); + for m in members.iter().take(300) { + if let Some(mp) = g.get_page(*m)? { + let mark = if mp.is_hub() { " (hub)" } else { "" }; + let _ = writeln!(out, "- [[{}]]{mark}", mp.title); + } + } + if members.len() > 300 { + let _ = writeln!(out, "- … {} more", members.len() - 300); + } + return Ok(out); + } + let mut tree = g.page_tree(page.id)?; + if let Some(b) = &p.block { + let id = parse_block_id(b)?; + let start = tree + .iter() + .position(|(_, b)| b.id == id) + .ok_or_else(|| err(format!("block {id} is not on [[{}]]", page.title)))?; + let base = tree[start].0; + let end = tree[start + 1..] + .iter() + .position(|(d, _)| *d <= base) + .map_or(tree.len(), |i| start + 1 + i); + tree = tree.drain(start..end).map(|(d, b)| (d - base, b)).collect(); + } + if let Some(max) = p.max_depth { + tree.retain(|(d, _)| *d <= max as usize); + } + let total = tree.len(); + let offset = parse_cursor(&p.cursor)?; + let lim = limit(p.limit, 400, 2000); + out.push('\n'); + if total == 0 { + out.push_str("(no blocks)\n"); + } + for (d, b) in tree.iter().skip(offset).take(lim) { + render_block(&mut out, *d, b, ids); + } + if offset + lim < total { + let _ = writeln!( + out, + "\n… {} more blocks; next cursor: {}", + total - offset - lim, + offset + lim + ); + } + Ok(out) +} + +/// `get_journal`: one day, or every existing journal in a range (oldest first). +pub fn get_journal(g: &Graph, p: &GetJournalParams) -> ToolResult { + let ids = p.ids.unwrap_or(true); + let days: Vec = if p.from.is_some() || p.to.is_some() { + let (from, to) = date_range(g, &p.from, &p.to, 6, MAX_RANGE_DAYS)?; + let mut v: Vec = g + .journals_between(from, to)? + .into_iter() + .filter_map(|j| j.journal_date) + .collect(); + v.reverse(); + if v.is_empty() { + return Ok(format!( + "No journals between {} and {}.", + journal_title(from), + journal_title(to) + )); + } + v + } else { + vec![match &p.date { + Some(d) if !d.trim().is_empty() => parse_date(g, d)?, + _ => g.today(), + }] + }; + let mut out = String::new(); + let mut budget = 1500usize; + for d in days { + let title = journal_title(d); + // Never `Graph::journal`: it would create the page. + let Some(page) = g.get_page(synapse_core::store::journal_id(d))? else { + let _ = writeln!(out, "# {title}\n(no journal)\n"); + continue; + }; + let tree = g.page_tree(page.id)?; + let _ = writeln!(out, "# {title}"); + if tree.is_empty() { + out.push_str("(empty)\n"); + } + for (depth, b) in &tree { + if budget == 0 { + out.push_str("… (output truncated; ask for a shorter range)\n"); + return Ok(out); + } + budget -= 1; + render_block(&mut out, *depth, b, ids); + } + out.push('\n'); + } + Ok(out.trim_end().to_string() + "\n") +} + +struct PageRow { + title: String, + journal: Option, + updated_at: i64, + template: bool, + hub: bool, +} + +fn page_rows(g: &Graph) -> Result, ToolError> { + let mut st = g + .conn() + .prepare("SELECT id, title, journal_date, updated_at, kind FROM pages")?; + let rows = st.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, Option>(2)?, + r.get::<_, i64>(3)?, + r.get::<_, String>(4)?, + )) + })?; + let mut out = HashMap::new(); + for r in rows { + let (id, title, jd, updated_at, kind) = r?; + let Ok(id) = Uuid::parse_str(&id) else { + continue; + }; + out.insert( + id, + PageRow { + title, + journal: jd.and_then(|d| NaiveDate::parse_from_str(&d, "%Y-%m-%d").ok()), + updated_at, + template: kind == "template", + hub: kind == "hub", + }, + ); + } + Ok(out) +} + +/// Pages allowed by the tag/type/hub/page filters (`None` = no filter). +fn page_filter( + g: &Graph, + tag: &Option, + ty: &Option, + hub: &Option, + page: &Option, +) -> Result>, ToolError> { + let mut set: Option> = None; + let mut narrow = |s: HashSet| { + set = Some(match set.take() { + Some(cur) => cur.intersection(&s).copied().collect(), + None => s, + }); + }; + if let Some(t) = tag.as_deref().filter(|t| !t.trim().is_empty()) { + narrow(g.pages_with_tag(t)?.into_iter().collect()); + } + if let Some(t) = ty.as_deref().filter(|t| !t.trim().is_empty()) { + let key = title_key(t); + narrow( + g.all_page_types()? + .into_iter() + .filter(|(_, ty)| title_key(ty) == key) + .map(|(id, _)| id) + .collect(), + ); + } + if let Some(h) = hub.as_deref().filter(|h| !h.trim().is_empty()) { + let hub = resolve_hub(g, h)?; + narrow(g.hub_members(hub.id)?.into_iter().collect()); + } + if let Some(p) = page.as_deref().filter(|p| !p.trim().is_empty()) { + narrow(std::iter::once(resolve_page(g, p)?.id).collect()); + } + Ok(set) +} + +/// `search`: substring scan over page titles/aliases and block text (all terms must match, +/// case/accent-insensitive), ranked by term frequency, title hits first. +pub fn search(g: &Graph, p: &SearchParams) -> ToolResult { + let terms = query_terms(&p.query); + if terms.is_empty() { + return Err(err("empty query")); + } + let scope = p.scope.as_deref().unwrap_or("all"); + let (want_pages, want_blocks) = match scope { + "all" | "" => (true, true), + "pages" => (true, false), + "blocks" => (false, true), + s => return Err(err(format!("bad scope {s:?}: all, pages or blocks"))), + }; + let journals = p.journals.as_deref().unwrap_or("any"); + if !matches!(journals, "any" | "only" | "exclude" | "") { + return Err(err(format!( + "bad journals {journals:?}: any, only or exclude" + ))); + } + let from = opt_date(g, &p.from)?; + let to = opt_date(g, &p.to)?; + let allowed = page_filter(g, &p.tag, &p.page_type, &p.hub, &p.page)?; + let pages = page_rows(g)?; + let keep = |id: &PageId, day: NaiveDate| -> bool { + let Some(row) = pages.get(id) else { + return false; + }; + if row.template || allowed.as_ref().is_some_and(|a| !a.contains(id)) { + return false; + } + match journals { + "only" if row.journal.is_none() => return false, + "exclude" if row.journal.is_some() => return false, + _ => {} + } + !(from.is_some_and(|f| day < f) || to.is_some_and(|t| day > t)) + }; + let phrase = fold(&one_line(&p.query.replace('"', ""))); + // (score, updated_at, line) + let mut hits: Vec<(f32, i64, String)> = Vec::new(); + if want_pages { + let mut aliases: HashMap> = HashMap::new(); + let mut st = g.conn().prepare("SELECT page_id, alias FROM aliases")?; + for r in st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? { + let (id, a) = r?; + if let Ok(id) = Uuid::parse_str(&id) { + aliases.entry(id).or_default().push(a); + } + } + for (id, row) in &pages { + let day = row.journal.unwrap_or_else(|| day_of_ms(row.updated_at)); + if !keep(id, day) { + continue; + } + let names = aliases.get(id).map(|a| a.join(" ")).unwrap_or_default(); + let hay = fold(&format!("{} {names}", row.title)); + if !terms.iter().all(|t| hay.contains(t.as_str())) { + continue; + } + let exact = fold(&row.title) == phrase; + let score = 100.0 + if exact { 100.0 } else { 0.0 }; + let mut line = format!("- [[{}]] (page", row.title); + if row.hub { + line.push_str(", hub"); + } + if !names.is_empty() { + let _ = write!(line, "; aliases: {}", aliases[id].join(", ")); + } + line.push(')'); + hits.push((score, row.updated_at, line)); + } + } + if want_blocks { + let mut st = g + .conn() + .prepare("SELECT id, page_id, content, updated_at FROM blocks")?; + let rows = st.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, i64>(3)?, + )) + })?; + for r in rows { + let (id, page_id, content, updated_at) = r?; + let Ok(pid) = Uuid::parse_str(&page_id) else { + continue; + }; + let Some(row) = pages.get(&pid) else { + continue; + }; + let day = row.journal.unwrap_or_else(|| day_of_ms(updated_at)); + if !keep(&pid, day) { + continue; + } + let hay = fold(&content); + if !terms.iter().all(|t| hay.contains(t.as_str())) { + continue; + } + let freq: usize = terms.iter().map(|t| count(&hay, t).min(5)).sum(); + let len = hay.chars().count() as f32; + let mut score = freq as f32 / (1.0 + len / 400.0); + if terms.len() > 1 && hay.contains(&phrase) { + score += 2.0; + } + let line = format!( + "- [[{}]] (({id})) {}: {}", + row.title, + journal_title(day), + snippet(&content, &terms, 200) + ); + hits.push((score, updated_at, line)); + } + } + hits.sort_by(|a, b| b.0.total_cmp(&a.0).then(b.1.cmp(&a.1))); + let total = hits.len(); + if total == 0 { + return Ok(format!("No results for {:?}.", p.query)); + } + let offset = parse_cursor(&p.cursor)?; + let lim = limit(p.limit, 20, 100); + let shown: Vec<&str> = hits + .iter() + .skip(offset) + .take(lim) + .map(|h| h.2.as_str()) + .collect(); + let mut out = format!( + "{total} results for {:?} (showing {}-{}):\n", + p.query, + offset + 1, + offset + shown.len() + ); + for l in shown { + out.push_str(l); + out.push('\n'); + } + if offset + lim < total { + let _ = writeln!(out, "next cursor: {}", offset + lim); + } + Ok(out) +} + +/// `list_pages`: filtered, sorted, paginated page index. +pub fn list_pages(g: &Graph, p: &ListPagesParams) -> ToolResult { + let journals = p.journals.as_deref().unwrap_or("exclude"); + let include = match journals { + "exclude" | "" => false, + "include" | "only" => true, + j => return Err(err(format!("bad journals {j:?}: exclude, include or only"))), + }; + let updated_since = opt_date(g, &p.updated_since)?; + let created_since = opt_date(g, &p.created_since)?; + let allowed = page_filter(g, &p.tag, &p.page_type, &p.hub, &None)?; + let untyped = p.untyped.unwrap_or(false); + let untagged = p.untagged.unwrap_or(false); + let mut pages: Vec = g + .list_pages(include, u32::MAX, 0)? + .into_iter() + .filter(|pg| journals != "only" || pg.is_journal()) + .filter(|pg| allowed.as_ref().is_none_or(|a| a.contains(&pg.id))) + .filter(|pg| !untyped || (!pg.is_journal() && !pg.is_hub() && pg.types.is_empty())) + .filter(|pg| !untagged || (!pg.is_journal() && !pg.is_hub() && pg.tags.is_empty())) + .filter(|pg| updated_since.is_none_or(|d| day_of_ms(pg.updated_at) >= d)) + .filter(|pg| created_since.is_none_or(|d| day_of_ms(pg.created_at) >= d)) + .collect(); + match p.sort.as_deref().unwrap_or("updated") { + "updated" | "" => pages.sort_by_key(|p| std::cmp::Reverse(p.updated_at)), + "created" => pages.sort_by_key(|p| std::cmp::Reverse(p.created_at)), + "title" => pages.sort_by_cached_key(|p| title_key(&p.title)), + s => return Err(err(format!("bad sort {s:?}: updated, created or title"))), + } + let total = pages.len(); + if total == 0 { + return Ok("No pages match.".into()); + } + let offset = parse_cursor(&p.cursor)?; + let lim = limit(p.limit, 50, 200); + let mut out = format!( + "{total} pages (showing {}-{}):\n", + offset + 1, + (offset + lim).min(total) + ); + for pg in pages.iter().skip(offset).take(lim) { + let mut parts = page_facets(g, pg)?; + if !pg.is_journal() { + parts.push(format!("updated {}", fmt_day(pg.updated_at))); + } + if parts.is_empty() { + let _ = writeln!(out, "- [[{}]]", pg.title); + } else { + let _ = writeln!(out, "- [[{}]] · {}", pg.title, parts.join(" · ")); + } + } + if offset + lim < total { + let _ = writeln!(out, "next cursor: {}", offset + lim); + } + Ok(out) +} + +/// `backlinks`: blocks linking to the page, grouped by source page, with parent context. +pub fn backlinks(g: &Graph, p: &PageRefParams) -> ToolResult { + let page = resolve_page(g, &p.page)?; + let links = g.backlinks(page.id)?; + if links.is_empty() { + return Ok(format!("No linked references to [[{}]].", page.title)); + } + let total = links.len(); + let offset = parse_cursor(&p.cursor)?; + let lim = limit(p.limit, 50, 200); + let n_pages = links + .iter() + .map(|l| l.block.page_id) + .collect::>() + .len(); + let mut out = format!( + "{total} linked references to [[{}]] from {n_pages} pages (showing {}-{}):\n", + page.title, + offset + 1, + (offset + lim).min(total) + ); + let mut current: Option = None; + for l in links.iter().skip(offset).take(lim) { + if current != Some(l.block.page_id) { + current = Some(l.block.page_id); + let _ = writeln!(out, "\n## [[{}]]", l.page_title); + } + if let Some(parent) = l + .block + .parent_id + .and_then(|id| g.get_block(id).ok().flatten()) + { + let _ = writeln!(out, "- under: {}", truncate(&parent.content, 100)); + } + let _ = writeln!( + out, + "- {} (({}))", + truncate(&l.block.content, 400), + l.block.id + ); + } + if offset + lim < total { + let _ = writeln!(out, "\nnext cursor: {}", offset + lim); + } + Ok(out) +} + +/// `related`: spreading activation over links, synapses and time. +pub fn related(g: &Graph, p: &PageRefParams) -> ToolResult { + let page = resolve_page(g, &p.page)?; + let lim = limit(p.limit, 15, 100); + let rel = g.related(page.id, lim)?; + if rel.is_empty() { + return Ok(format!("Nothing related to [[{}]] yet.", page.title)); + } + let mut out = format!("Related to [[{}]] (strongest first):\n", page.title); + for (id, score) in rel { + if let Some(r) = g.get_page(id)? { + let _ = writeln!(out, "- [[{}]] ({score:.2})", r.title); + } + } + Ok(out) +} + +/// `list_tags`: tags in use with page counts. +pub fn list_tags(g: &Graph, p: &ListParams) -> ToolResult { + let tags = g.tag_catalog()?; + if tags.is_empty() { + return Ok("No tags in use.".into()); + } + let lim = limit(p.limit, 100, 1000); + let mut out = format!( + "{} tags (pages: total; explicit/from type/from hub):\n", + tags.len() + ); + for t in tags.iter().take(lim) { + let _ = writeln!( + out, + "- {} — {} ({}/{}/{})", + t.name, t.count, t.explicit, t.typed, t.from_hub + ); + } + if tags.len() > lim { + let _ = writeln!(out, "… {} more (raise `limit`)", tags.len() - lim); + } + Ok(out) +} + +/// `list_types`: types in use (with counts and icons), defined ones, then suggestions. +pub fn list_types(g: &Graph, p: &ListParams) -> ToolResult { + let types = g.type_catalog()?; + let lim = limit(p.limit, 100, 1000); + let (used, unused): (Vec<_>, Vec<_>) = types.iter().partition(|t| t.count > 0); + let mut out = format!("{} types in use:\n", used.len()); + for t in used.iter().take(lim) { + let icon = t + .icon + .as_deref() + .map(|i| format!("{i} ")) + .unwrap_or_default(); + let _ = writeln!(out, "- {icon}{} — {} pages", t.name, t.count); + } + let defined: Vec<&str> = unused + .iter() + .filter(|t| !t.suggested) + .map(|t| t.name.as_str()) + .collect(); + let suggested: Vec<&str> = unused + .iter() + .filter(|t| t.suggested) + .map(|t| t.name.as_str()) + .collect(); + if !defined.is_empty() { + let _ = writeln!(out, "Defined, unused: {}", defined.join(", ")); + } + if !suggested.is_empty() { + let _ = writeln!(out, "Suggested, unused: {}", suggested.join(", ")); + } + Ok(out) +} + +/// `hubs`: the hub tree (or one hub's members). +pub fn hubs(g: &Graph, p: &HubsParams) -> ToolResult { + if let Some(h) = p.hub.as_deref().filter(|h| !h.trim().is_empty()) { + let hub = resolve_hub(g, h)?; + let members = g.hub_members(hub.id)?; + let mut out = format!("# {} ({} members)\n", hub.title, members.len()); + if !hub.description.is_empty() { + let _ = writeln!(out, "{}", truncate(&hub.description, 300)); + } + for m in members { + if let Some(mp) = g.get_page(m)? { + let mut parts = page_facets(g, &mp)?; + parts.retain(|f| !f.starts_with("hub:")); + let suffix = if parts.is_empty() { + String::new() + } else { + format!(" · {}", parts.join(" · ")) + }; + let _ = writeln!(out, "- [[{}]]{suffix}", mp.title); + } + } + return Ok(out); + } + let st = g.structure()?; + if st.hubs.is_empty() { + return Ok("No hubs.".into()); + } + let by_id: HashMap = + st.hubs.iter().map(|h| (h.page, h)).collect(); + let nested: HashSet = st + .hubs + .iter() + .flat_map(|h| h.members.iter().copied()) + .filter(|m| by_id.contains_key(m)) + .collect(); + let mut roots: Vec<&synapse_core::HubInfo> = st + .hubs + .iter() + .filter(|h| !nested.contains(&h.page)) + .collect(); + roots.sort_by_cached_key(|h| title_key(&h.title)); + let members = p.members.unwrap_or(false); + let mut out = format!("{} hubs:\n", st.hubs.len()); + let mut seen = HashSet::new(); + fn walk( + g: &Graph, + out: &mut String, + h: &synapse_core::HubInfo, + depth: usize, + by_id: &HashMap, + seen: &mut HashSet, + members: bool, + ) -> Result<(), ToolError> { + if !seen.insert(h.page) { + return Ok(()); + } + let pad = " ".repeat(depth); + let notes: Vec = h + .members + .iter() + .copied() + .filter(|m| !by_id.contains_key(m)) + .collect(); + let desc = if h.description.is_empty() { + String::new() + } else { + format!(" — {}", truncate(&h.description, 80)) + }; + let _ = writeln!(out, "{pad}- [[{}]] ({} notes){desc}", h.title, notes.len()); + let mut subs: Vec<&synapse_core::HubInfo> = h + .members + .iter() + .filter_map(|m| by_id.get(m).copied()) + .collect(); + subs.sort_by_cached_key(|s| title_key(&s.title)); + for s in subs { + walk(g, out, s, depth + 1, by_id, seen, members)?; + } + if members { + for n in notes { + if let Some(np) = g.get_page(n)? { + let _ = writeln!(out, "{pad} - {}", np.title); + } + } + } + Ok(()) + } + for r in roots { + walk(g, &mut out, r, 0, &by_id, &mut seen, members)?; + } + // Hubs only reachable through a cycle. + for h in &st.hubs { + walk(g, &mut out, h, 0, &by_id, &mut seen, members)?; + } + Ok(out) +} + +/// `timeline`: per day, the journal, pages born and pages edited. +pub fn timeline(g: &Graph, p: &RangeParams) -> ToolResult { + let (from, to) = date_range(g, &p.from, &p.to, 6, MAX_TIMELINE_DAYS)?; + let days = g.timeline(from, to)?; + let mut titles: HashMap = HashMap::new(); + let mut title = |id: PageId| -> Result { + if let Some(t) = titles.get(&id) { + return Ok(t.clone()); + } + let t = g.get_page(id)?.map(|p| p.title).unwrap_or_default(); + titles.insert(id, t.clone()); + Ok(t) + }; + let mut out = format!( + "Timeline {} → {}:\n", + journal_title(from), + journal_title(to) + ); + let mut any = false; + for d in days { + if d.journal.is_none() && d.created.is_empty() && d.edited.is_empty() { + continue; + } + any = true; + let mark = if d.journal.is_some() { + " (journal)" + } else { + "" + }; + let _ = writeln!(out, "\n## {}{mark}", journal_title(d.date)); + if !d.created.is_empty() { + let mut names = Vec::new(); + for id in &d.created { + names.push(format!("[[{}]]", title(*id)?)); + } + let _ = writeln!(out, "- born: {}", names.join(", ")); + } + if !d.edited.is_empty() { + let mut names = Vec::new(); + for (id, n) in &d.edited { + names.push(format!("[[{}]] ×{n}", title(*id)?)); + } + let _ = writeln!(out, "- edited: {}", names.join(", ")); + } + } + if !any { + out.push_str("(nothing)\n"); + } + Ok(out) +} + +/// `journal_links`: per journal day, the pages it links (with their curation status) and +/// existing pages it mentions without linking. +pub fn journal_links(g: &Graph, p: &RangeParams) -> ToolResult { + let (from, to) = date_range(g, &p.from, &p.to, 6, MAX_RANGE_DAYS)?; + let mut journals = g.journals_between(from, to)?; + journals.reverse(); + if journals.is_empty() { + return Ok(format!( + "No journals between {} and {}.", + journal_title(from), + journal_title(to) + )); + } + // Candidate titles for unlinked mentions: notes and hubs, at least 3 chars. + let candidates: Vec<(String, String)> = g + .all_titles()? + .into_iter() + .filter_map(|(t, id)| { + let f = fold(t.trim()); + (f.chars().count() >= 3 && NaiveDate::parse_from_str(&t, "%Y-%m-%d").is_err()) + .then_some((f, t)) + .filter(|_| { + g.get_page(id) + .ok() + .flatten() + .is_some_and(|p| !p.is_journal() && !p.is_template()) + }) + }) + .collect(); + let mut out = String::new(); + for j in journals { + let tree = g.page_tree(j.id)?; + let mut linked: Vec = Vec::new(); + let mut linked_keys: HashSet = HashSet::new(); + let mut text = String::new(); + for (_, b) in &tree { + for (t, _) in extract_refs(&b.content).pages { + if linked_keys.insert(title_key(&t)) { + linked.push(t); + } + } + text.push_str(&strip_links(&b.content)); + text.push('\n'); + } + let hay = fold(&text); + let mut mentions: Vec<&str> = candidates + .iter() + .filter(|(f, t)| !linked_keys.contains(&title_key(t)) && contains_word(&hay, f)) + .map(|(_, t)| t.as_str()) + .collect(); + mentions.sort_by_key(|t| title_key(t)); + mentions.dedup_by_key(|t| title_key(t)); + if linked.is_empty() && mentions.is_empty() { + continue; + } + let _ = writeln!(out, "## {}", j.title); + for t in &linked { + let status = match g.page_by_title(t)? { + Some(pg) if pg.is_journal() => continue, + Some(pg) => { + let mut s = page_facets(g, &pg)?; + if pg.types.is_empty() && !pg.is_hub() { + s.push("untyped".into()); + } + if pg.tags.is_empty() && !pg.is_hub() { + s.push("untagged".into()); + } + if !pg.is_hub() && page_block_count(g, pg.id)? == 0 { + s.push("empty".into()); + } + s.join(" · ") + } + None => "missing".into(), + }; + let _ = writeln!(out, "- linked [[{t}]] · {status}"); + } + for t in mentions { + let _ = writeln!(out, "- mentioned (not linked) [[{t}]]"); + } + out.push('\n'); + } + if out.is_empty() { + out.push_str("No page links or mentions in that range.\n"); + } + Ok(out) +} + +/// Drops `[[links]]`, `#tags` and `((refs))` so only free text is left. +fn strip_links(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find("[[") { + out.push_str(&rest[..i]); + match rest[i..].find("]]") { + Some(j) => rest = &rest[i + j + 2..], + None => { + rest = ""; + } + } + } + out.push_str(rest); + out.split_whitespace() + .filter(|w| !w.starts_with('#') && !w.starts_with("((")) + .collect::>() + .join(" ") +} + +// ------------------------------------------------------------------- writes + +/// Inserts a Markdown outline under `parent` (or at the page's end). Returns the new +/// top-level blocks and the total count. Logseq `id::` properties are ignored (new ids). +fn insert_outline( + g: &Graph, + page: PageId, + parent: Option, + text: &str, +) -> Result<(Vec, usize, synapse_core::Properties), ToolError> { + let outline = synapse_import::outline::parse_markdown(text); + let mut ids: Vec = Vec::with_capacity(outline.blocks.len()); + let mut top = Vec::new(); + for b in &outline.blocks { + let under = match b.parent { + Some(i) => Some(*ids.get(i).ok_or_else(|| err("malformed outline"))?), + None => parent, + }; + let blk = g.insert_block(page, Placement::LastChildOf(under), &b.content)?; + if !b.properties.is_empty() { + g.set_block_properties(blk.id, b.properties.clone())?; + } + if b.collapsed { + g.set_collapsed(blk.id, true)?; + } + if b.parent.is_none() { + top.push(blk.id); + } + ids.push(blk.id); + } + Ok((top, ids.len(), outline.page_props)) +} + +fn clean_list(v: &Option>) -> Vec { + v.iter() + .flatten() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() +} + +/// `create_page`. +pub fn create_page(g: &Graph, p: &CreatePageParams) -> ToolResult { + let title = p.title.trim(); + if NaiveDate::parse_from_str(title, "%Y-%m-%d").is_ok() { + return Err(err("journals are read-only here; pick a non-date title")); + } + let origin = match opt_date(g, &p.source_journal)? { + Some(d) => { + // Must exist: the page is born there and journals are never created here. + if g.get_page(synapse_core::store::journal_id(d))?.is_none() { + return Err(err(format!("no journal for {}", journal_title(d)))); + } + Some(d) + } + None => None, + }; + let hub = p + .hub + .as_deref() + .filter(|h| !h.trim().is_empty()) + .map(|h| resolve_hub(g, h)) + .transpose()?; + let page = g.create_page(synapse_core::NewPage { + title: title.to_string(), + origin_journal: origin, + ..Default::default() + })?; + if let Some(t) = p.page_type.as_deref().filter(|t| !t.trim().is_empty()) { + g.set_page_type(page.id, Some(t))?; + } + let tags = clean_list(&p.tags); + if !tags.is_empty() { + g.set_page_tags(page.id, tags)?; + } + if let Some(h) = hub { + g.add_to_hub(page.id, h.id)?; + } + let mut n = 0; + if let Some(c) = p.content.as_deref().filter(|c| !c.trim().is_empty()) { + let (_, count, props) = insert_outline(g, page.id, None, c)?; + n = count; + if !props.is_empty() { + g.set_page_properties(page.id, props)?; + } + } + let page = g.get_page(page.id)?.unwrap_or(page); + let facets = page_facets(g, &page)?; + let mut out = format!( + "Created [[{}]] (id {}) with {n} blocks", + page.title, page.id + ); + if !facets.is_empty() { + let _ = write!(out, " · {}", facets.join(" · ")); + } + out.push('\n'); + Ok(out) +} + +/// `append_blocks` (pages only). +pub fn append_blocks(g: &Graph, p: &AppendBlocksParams) -> ToolResult { + let page = writable_page(g, &p.page)?; + if page.is_hub() { + return Err(err("hubs have no blocks; append to a member page")); + } + let parent = match p.parent.as_deref().filter(|s| !s.trim().is_empty()) { + Some(b) => { + let b = get_block(g, b)?; + if b.page_id != page.id { + return Err(err(format!("block {} is not on [[{}]]", b.id, page.title))); + } + Some(b.id) + } + None => None, + }; + if p.content.trim().is_empty() { + return Err(err("empty content")); + } + let (top, n, props) = insert_outline(g, page.id, parent, &p.content)?; + let mut out = format!("Appended {n} blocks to [[{}]]", page.title); + if !props.is_empty() { + // Leading `key:: value` lines are page properties (Logseq): merge them. + let keys: Vec = props.keys().cloned().collect(); + let mut merged = page.properties.clone(); + merged.extend(props); + g.set_page_properties(page.id, merged)?; + let _ = write!(out, " (page properties set: {})", keys.join(", ")); + } + out.push_str(":\n"); + for id in top { + if let Some(b) = g.get_block(id)? { + let _ = writeln!(out, "- {} (({id}))", truncate(&b.content, 80)); + } + } + Ok(out) +} + +fn block_page(g: &Graph, b: &Block) -> Result { + let page = g + .get_page(b.page_id)? + .ok_or_else(|| err(format!("page of block {} not found", b.id)))?; + ensure_writable(&page)?; + Ok(page) +} + +/// `update_block` (pages only). +pub fn update_block(g: &Graph, p: &UpdateBlockParams) -> ToolResult { + let b = get_block(g, &p.block)?; + let page = block_page(g, &b)?; + let b = g.update_block(b.id, &p.content)?; + Ok(format!( + "Updated (({})) on [[{}]]: {}\n", + b.id, + page.title, + truncate(&b.content, 120) + )) +} + +/// `delete_block` (pages only; deletes the subtree). +pub fn delete_block(g: &Graph, p: &DeleteBlockParams) -> ToolResult { + let b = get_block(g, &p.block)?; + let page = block_page(g, &b)?; + let tree = g.page_tree(page.id)?; + let start = tree.iter().position(|(_, x)| x.id == b.id).unwrap_or(0); + let base = tree.get(start).map_or(0, |t| t.0); + let n = 1 + tree[start + 1..] + .iter() + .take_while(|(d, _)| *d > base) + .count(); + g.delete_block(b.id)?; + Ok(format!( + "Deleted (({})) and {} children from [[{}]]\n", + b.id, + n - 1, + page.title + )) +} + +/// `set_page_type`. +pub fn set_page_type(g: &Graph, p: &SetPageTypeParams) -> ToolResult { + let page = writable_page(g, &p.page)?; + let ty = p.page_type.as_deref().filter(|t| !t.trim().is_empty()); + let page = g.set_page_type(page.id, ty)?; + Ok(match page.page_type() { + Some(t) => format!("[[{}]] is now of type {t}\n", page.title), + None => format!("[[{}]] has no type now\n", page.title), + }) +} + +/// `set_page_tags`: replace, add and/or remove explicit tags. +pub fn set_page_tags(g: &Graph, p: &SetPageTagsParams) -> ToolResult { + let page = writable_page(g, &p.page)?; + let mut tags = match &p.tags { + Some(_) => clean_list(&p.tags), + None => page.tags.clone(), + }; + tags.extend(clean_list(&p.add)); + let remove: HashSet = clean_list(&p.remove).iter().map(|t| title_key(t)).collect(); + tags.retain(|t| !remove.contains(&title_key(t))); + let page = g.set_page_tags(page.id, tags)?; + Ok(if page.tags.is_empty() { + format!("[[{}]] has no tags now\n", page.title) + } else { + format!("[[{}]] tags: {}\n", page.title, page.tags.join(", ")) + }) +} + +/// `set_page_hub`: move a page into a hub, or out of its hub. +pub fn set_page_hub(g: &Graph, p: &SetPageHubParams) -> ToolResult { + let page = writable_page(g, &p.page)?; + match p.hub.as_deref().filter(|h| !h.trim().is_empty()) { + Some(h) => { + let hub = resolve_hub(g, h)?; + g.add_to_hub(page.id, hub.id)?; + Ok(format!( + "[[{}]] is now in hub [[{}]]\n", + page.title, hub.title + )) + } + None => { + g.set_page_hubs(page.id, Vec::new())?; + Ok(format!("[[{}]] is in no hub now\n", page.title)) + } + } +} + +/// Renders a page for `synapse://` resources. +pub fn page_resource(g: &Graph, page: &str) -> ToolResult { + get_page( + g, + &GetPageParams { + page: page.to_string(), + ids: Some(false), + limit: Some(2000), + ..Default::default() + }, + ) +} diff --git a/crates/synapse-mcp/tests/stdio.rs b/crates/synapse-mcp/tests/stdio.rs new file mode 100644 index 0000000..87b8c30 --- /dev/null +++ b/crates/synapse-mcp/tests/stdio.rs @@ -0,0 +1,163 @@ +//! Smoke test of the `synapse-mcp` binary over stdio: initialize, tools/list, tools/call. + +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc; +use std::time::Duration; +use synapse_core::{Graph, NewPage, Placement}; + +struct Server { + child: Child, + stdin: ChildStdin, + lines: mpsc::Receiver, +} + +impl Server { + fn start(graph: &std::path::Path, extra: &[&str]) -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_synapse-mcp")) + .arg("--graph") + .arg(graph) + .args(extra) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, lines) = mpsc::channel(); + std::thread::spawn(move || { + for l in BufReader::new(stdout).lines() { + let Ok(l) = l else { break }; + if tx.send(l).is_err() { + break; + } + } + }); + Self { + child, + stdin, + lines, + } + } + + fn send(&mut self, msg: Value) { + writeln!(self.stdin, "{msg}").unwrap(); + self.stdin.flush().unwrap(); + } + + /// The response to request `id` (skipping notifications). + fn call(&mut self, id: u64, method: &str, params: Value) -> Value { + self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); + loop { + let line = self + .lines + .recv_timeout(Duration::from_secs(20)) + .expect("server reply"); + let v: Value = serde_json::from_str(&line).unwrap(); + if v["id"] == json!(id) { + return v; + } + } + } + + fn init(&mut self) -> Value { + let r = self.call( + 1, + "initialize", + json!({"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}}), + ); + self.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); + r + } +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn tool_names(list: &Value) -> Vec { + list["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect() +} + +#[test] +fn stdio_initialize_list_and_call() { + let dir = tempfile::tempdir().unwrap(); + { + let g = Graph::open(dir.path()).unwrap(); + let p = g.create_page(NewPage::titled("Rust")).unwrap(); + g.insert_block( + p.id, + Placement::LastChildOf(None), + "ownership and borrowing", + ) + .unwrap(); + } + let mut s = Server::start(dir.path(), &[]); + let init = s.init(); + assert_eq!( + init["result"]["serverInfo"]["name"], "synapse-mcp", + "{init}" + ); + let names = tool_names(&s.call(2, "tools/list", json!({}))); + assert!(names.contains(&"search".to_string()), "{names:?}"); + assert!( + !names.contains(&"create_page".to_string()), + "read-only: {names:?}" + ); + let r = s.call( + 3, + "tools/call", + json!({"name": "search", "arguments": {"query": "borrowing"}}), + ); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("[[Rust]]"), "{r}"); + // Write tools are not callable read-only. + let r = s.call( + 4, + "tools/call", + json!({"name": "create_page", "arguments": {"title": "X"}}), + ); + assert!( + r.get("error").is_some() || r["result"]["isError"] == json!(true), + "{r}" + ); + drop(s); + + let mut s = Server::start(dir.path(), &["--allow-write"]); + s.init(); + let names = tool_names(&s.call(2, "tools/list", json!({}))); + assert!(names.contains(&"create_page".to_string()), "{names:?}"); + let r = s.call( + 3, + "tools/call", + json!({"name": "create_page", "arguments": {"title": "Borrow checker", "type": "Concept"}}), + ); + assert_eq!(r["result"]["isError"], json!(false), "{r}"); + drop(s); + let g = Graph::open(dir.path()).unwrap(); + let p = g.page_by_title("borrow checker").unwrap().unwrap(); + assert_eq!(p.page_type(), Some("Concept")); +} + +#[test] +fn refuses_a_missing_graph() { + let dir = tempfile::tempdir().unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_synapse-mcp")) + .arg("--graph") + .arg(dir.path().join("nope")) + .output() + .unwrap(); + assert!(!out.status.success()); + assert!(!dir.path().join("nope").exists(), "must not create a graph"); +} diff --git a/crates/synapse-mcp/tests/tools.rs b/crates/synapse-mcp/tests/tools.rs new file mode 100644 index 0000000..d755dc9 --- /dev/null +++ b/crates/synapse-mcp/tests/tools.rs @@ -0,0 +1,622 @@ +//! Every tool on a temp graph, through the same read/write wrappers the server uses. + +use chrono::NaiveDate; +use synapse_core::{Graph, NewPage, Placement}; +use synapse_mcp::params::*; +use synapse_mcp::tools::{self, ToolResult}; +use synapse_mcp::{read_job, write_job}; + +fn day(s: &str) -> NaiveDate { + NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap() +} + +/// 2026-03-10 is "today". Journals on 03-08 and 03-10; a typed+tagged book in hub "Reading". +fn fixture() -> (tempfile::TempDir, Graph) { + let dir = tempfile::tempdir().unwrap(); + let g = Graph::open(dir.path()).unwrap(); + let noon = |d: &str| { + day(d) + .and_hms_opt(12, 0, 0) + .unwrap() + .and_local_timezone(chrono::Local) + .unwrap() + .timestamp_millis() + }; + g.set_now(Some(noon("2026-03-08"))); + let j1 = g.journal(day("2026-03-08")).unwrap(); + let b = g + .insert_block( + j1.id, + Placement::LastChildOf(None), + "Started reading [[Dune]] by Frank Herbert", + ) + .unwrap(); + g.insert_block( + j1.id, + Placement::LastChildOf(Some(b.id)), + "the canción of spice", + ) + .unwrap(); + let hub = g.create_hub("Reading", "Books and articles").unwrap(); + let dune = g.page_by_title("Dune").unwrap().unwrap(); + g.set_page_type(dune.id, Some("Book")).unwrap(); + g.set_page_tags(dune.id, vec!["scifi".into()]).unwrap(); + g.add_to_hub(dune.id, hub.id).unwrap(); + g.insert_block( + dune.id, + Placement::LastChildOf(None), + "Arrakis is a desert planet", + ) + .unwrap(); + g.set_now(Some(noon("2026-03-10"))); + let j2 = g.journal(day("2026-03-10")).unwrap(); + g.insert_block( + j2.id, + Placement::LastChildOf(None), + "Talked about Dune and [[Gardening]] with Ana", + ) + .unwrap(); + (dir, g) +} + +fn read(g: &Graph, f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static) -> String { + read_job(f)(g).unwrap_or_else(|e| panic!("tool failed: {e}")) +} + +fn read_err(g: &Graph, f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static) -> String { + read_job(f)(g).expect_err("expected an error").message +} + +fn write(g: &Graph, f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static) -> ToolResult { + write_job(f)(g) +} + +#[test] +fn search_finds_blocks_and_titles_with_filters() { + let (_d, g) = fixture(); + let out = read(&g, |g| { + tools::search( + g, + &SearchParams { + query: "dune".into(), + ..Default::default() + }, + ) + }); + assert!(out.starts_with("3 results"), "{out}"); + assert!( + out.lines().nth(1).unwrap().contains("[[Dune]] (page"), + "{out}" + ); + assert!(out.contains("[[2026-03-08]] (("), "{out}"); + // Accent-insensitive, journals only, date filter. + let out = read(&g, |g| { + tools::search( + g, + &SearchParams { + query: "cancion".into(), + journals: Some("only".into()), + from: Some("2026-03-08".into()), + to: Some("2026-03-08".into()), + ..Default::default() + }, + ) + }); + assert!(out.contains("canción of spice"), "{out}"); + // Tag filter keeps only the tagged page's content. + let out = read(&g, |g| { + tools::search( + g, + &SearchParams { + query: "arrakis".into(), + tag: Some("scifi".into()), + ..Default::default() + }, + ) + }); + assert!(out.starts_with("1 results"), "{out}"); + let out = read(&g, |g| { + tools::search( + g, + &SearchParams { + query: "dune".into(), + limit: Some(1), + ..Default::default() + }, + ) + }); + assert!(out.contains("next cursor: 1"), "{out}"); + assert!(read_err(&g, |g| tools::search(g, &SearchParams::default())).contains("empty")); +} + +#[test] +fn get_page_renders_header_and_outline() { + let (_d, g) = fixture(); + let out = read(&g, |g| { + tools::get_page( + g, + &GetPageParams { + page: "dune".into(), + ..Default::default() + }, + ) + }); + assert!(out.starts_with("# Dune\n"), "{out}"); + assert!(out.contains("- type: Book"), "{out}"); + assert!(out.contains("- tags: scifi"), "{out}"); + assert!(out.contains("- hub: Reading"), "{out}"); + assert!(out.contains("born in [[2026-03-08]]"), "{out}"); + assert!(out.contains("- Arrakis is a desert planet (("), "{out}"); + // Journal by date, subtree and depth, no ids. + let out = read(&g, |g| { + tools::get_page( + g, + &GetPageParams { + page: "2026-03-08".into(), + max_depth: Some(0), + ids: Some(false), + ..Default::default() + }, + ) + }); + assert!( + out.contains("- Started reading [[Dune]] by Frank Herbert\n"), + "{out}" + ); + assert!(!out.contains("spice"), "{out}"); + // Hub lists members. + let out = read(&g, |g| { + tools::get_page( + g, + &GetPageParams { + page: "Reading".into(), + ..Default::default() + }, + ) + }); + assert!(out.contains("## Members (1)\n- [[Dune]]"), "{out}"); + let e = read_err(&g, |g| { + tools::get_page( + g, + &GetPageParams { + page: "Dun".into(), + ..Default::default() + }, + ) + }); + assert!(e.contains("did you mean: [[Dune]]"), "{e}"); +} + +#[test] +fn get_journal_day_and_range_never_create() { + let (_d, g) = fixture(); + let seq = g.last_seq().unwrap(); + let out = read(&g, |g| { + tools::get_journal( + g, + &GetJournalParams { + date: Some("today".into()), + ..Default::default() + }, + ) + }); + assert!(out.starts_with("# 2026-03-10\n- Talked about"), "{out}"); + let out = read(&g, |g| { + tools::get_journal( + g, + &GetJournalParams { + date: Some("2026-03-09".into()), + ..Default::default() + }, + ) + }); + assert!(out.contains("(no journal)"), "{out}"); + let out = read(&g, |g| { + tools::get_journal( + g, + &GetJournalParams { + from: Some("2026-03-01".into()), + ..Default::default() + }, + ) + }); + let a = out.find("# 2026-03-08").unwrap(); + let b = out.find("# 2026-03-10").unwrap(); + assert!(a < b, "oldest first: {out}"); + assert_eq!(g.last_seq().unwrap(), seq, "reads must not write"); + assert!( + g.get_page(synapse_core::store::journal_id(day("2026-03-09"))) + .unwrap() + .is_none() + ); +} + +#[test] +fn list_pages_filters_and_sorts() { + let (_d, g) = fixture(); + let out = read(&g, |g| tools::list_pages(g, &ListPagesParams::default())); + assert!( + out.contains("- [[Dune]] · type: Book · tags: scifi · hub: Reading"), + "{out}" + ); + assert!(!out.contains("[[2026-03-08]]"), "journals excluded: {out}"); + let out = read(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + untyped: Some(true), + ..Default::default() + }, + ) + }); + assert!( + out.contains("[[Gardening]]") && !out.contains("[[Dune]]"), + "{out}" + ); + assert!(!out.contains("[[Reading]]"), "hubs excluded: {out}"); + let out = read(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + page_type: Some("book".into()), + ..Default::default() + }, + ) + }); + assert!(out.starts_with("1 pages"), "{out}"); + let out = read(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + journals: Some("only".into()), + sort: Some("title".into()), + ..Default::default() + }, + ) + }); + assert!( + out.find("2026-03-08").unwrap() < out.find("2026-03-10").unwrap(), + "{out}" + ); + let out = read(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + created_since: Some("2026-03-10".into()), + ..Default::default() + }, + ) + }); + assert!( + out.contains("[[Gardening]]") && !out.contains("[[Dune]]"), + "{out}" + ); +} + +#[test] +fn backlinks_and_related() { + let (_d, g) = fixture(); + let out = read(&g, |g| { + tools::backlinks( + g, + &PageRefParams { + page: "Dune".into(), + ..Default::default() + }, + ) + }); + assert!( + out.starts_with("1 linked references to [[Dune]] from 1 pages"), + "{out}" + ); + assert!( + out.contains("## [[2026-03-08]]\n- Started reading"), + "{out}" + ); + let out = read(&g, |g| { + tools::related( + g, + &PageRefParams { + page: "Dune".into(), + ..Default::default() + }, + ) + }); + assert!(out.contains("[[2026-03-08]]"), "{out}"); +} + +#[test] +fn tags_types_hubs_timeline() { + let (_d, g) = fixture(); + let out = read(&g, |g| tools::list_tags(g, &ListParams::default())); + assert!(out.contains("- scifi — 1 (1/0/0)"), "{out}"); + assert!(out.contains("- Book — 1 (0/1/0)"), "{out}"); + assert!(out.contains("- Reading — 1 (0/0/1)"), "{out}"); + let out = read(&g, |g| tools::list_types(g, &ListParams::default())); + assert!( + out.starts_with("1 types in use:\n- Book — 1 pages"), + "{out}" + ); + let out = read(&g, |g| { + tools::hubs( + g, + &HubsParams { + members: Some(true), + ..Default::default() + }, + ) + }); + assert!( + out.contains("- [[Reading]] (1 notes) — Books and articles\n - Dune"), + "{out}" + ); + let out = read(&g, |g| { + tools::hubs( + g, + &HubsParams { + hub: Some("Reading".into()), + ..Default::default() + }, + ) + }); + assert!( + out.contains("- [[Dune]] · type: Book · tags: scifi"), + "{out}" + ); + let out = read(&g, |g| tools::timeline(g, &RangeParams::default())); + assert!(out.contains("## 2026-03-08 (journal)\n- born: "), "{out}"); + assert!(out.contains("[[Dune]]"), "{out}"); + let e = read_err(&g, |g| { + tools::timeline( + g, + &RangeParams { + from: Some("2025-01-01".into()), + to: None, + }, + ) + }); + assert!(e.contains("range too long"), "{e}"); +} + +#[test] +fn journal_links_reports_status_and_unlinked_mentions() { + let (_d, g) = fixture(); + let out = read(&g, |g| tools::journal_links(g, &RangeParams::default())); + assert!( + out.contains("## 2026-03-08\n- linked [[Dune]] · type: Book"), + "{out}" + ); + assert!( + out.contains("- linked [[Gardening]] · untyped · untagged · empty"), + "{out}" + ); + assert!(out.contains("- mentioned (not linked) [[Dune]]"), "{out}"); +} + +#[test] +fn write_tools_curate_pages() { + let (_d, g) = fixture(); + let out = write(&g, |g| { + tools::create_page( + g, + &CreatePageParams { + title: "Frank Herbert".into(), + page_type: Some("Person".into()), + tags: Some(vec!["author".into(), "scifi".into()]), + hub: Some("Reading".into()), + content: Some("- Wrote [[Dune]]\n - 1965\n- born:: 1920".into()), + source_journal: Some("2026-03-08".into()), + }, + ) + }) + .unwrap(); + assert!(out.starts_with("Created [[Frank Herbert]]"), "{out}"); + assert!(out.contains("with 3 blocks"), "{out}"); + let p = g.page_by_title("frank herbert").unwrap().unwrap(); + assert_eq!(p.page_type(), Some("Person")); + assert_eq!(p.tags, vec!["author", "scifi"]); + assert_eq!(p.origin_journal, Some(day("2026-03-08"))); + let tree = g.page_tree(p.id).unwrap(); + assert_eq!(tree[1].0, 1, "nested child"); + // Duplicate title. + let e = write(&g, |g| { + tools::create_page( + g, + &CreatePageParams { + title: "Dune".into(), + ..Default::default() + }, + ) + }) + .unwrap_err(); + assert!(e.message.contains("already exists"), "{e}"); + + let out = write(&g, |g| { + tools::append_blocks( + g, + &AppendBlocksParams { + page: "Frank Herbert".into(), + content: "- Also wrote [[Children of Dune]]".into(), + parent: None, + }, + ) + }) + .unwrap(); + assert!(out.starts_with("Appended 1 blocks"), "{out}"); + let first = g.page_tree(p.id).unwrap()[0].1.id; + let out = write(&g, move |g| { + tools::update_block( + g, + &UpdateBlockParams { + block: format!("(({first}))"), + content: "Wrote [[Dune]] (1965)".into(), + }, + ) + }) + .unwrap(); + assert!(out.contains("Wrote [[Dune]] (1965)"), "{out}"); + let out = write(&g, move |g| { + tools::delete_block( + g, + &DeleteBlockParams { + block: first.to_string(), + }, + ) + }) + .unwrap(); + assert!(out.contains("and 1 children"), "{out}"); + + write(&g, |g| { + tools::set_page_type( + g, + &SetPageTypeParams { + page: "Gardening".into(), + page_type: Some("Topic".into()), + }, + ) + }) + .unwrap(); + let out = write(&g, |g| { + tools::set_page_tags( + g, + &SetPageTagsParams { + page: "Gardening".into(), + add: Some(vec!["hobby".into(), "outdoors".into()]), + remove: Some(vec!["Outdoors".into()]), + ..Default::default() + }, + ) + }) + .unwrap(); + assert_eq!(out, "[[Gardening]] tags: hobby\n"); + let out = write(&g, |g| { + tools::set_page_hub( + g, + &SetPageHubParams { + page: "Gardening".into(), + hub: Some("Reading".into()), + }, + ) + }) + .unwrap(); + assert!(out.contains("now in hub [[Reading]]"), "{out}"); + write(&g, |g| { + tools::set_page_hub( + g, + &SetPageHubParams { + page: "Gardening".into(), + hub: None, + }, + ) + }) + .unwrap(); + let gp = g.page_by_title("Gardening").unwrap().unwrap(); + assert_eq!(gp.page_type(), Some("Topic")); + assert!(gp.hubs.is_empty()); +} + +#[test] +fn write_tools_refuse_journals_and_roll_back_on_error() { + let (_d, g) = fixture(); + let jblock = g + .page_tree(synapse_core::store::journal_id(day("2026-03-10"))) + .unwrap()[0] + .1 + .id; + let seq = g.last_seq().unwrap(); + for e in [ + write(&g, |g| { + tools::append_blocks( + g, + &AppendBlocksParams { + page: "today".into(), + content: "- x".into(), + parent: None, + }, + ) + }), + write(&g, move |g| { + tools::update_block( + g, + &UpdateBlockParams { + block: jblock.to_string(), + content: "x".into(), + }, + ) + }), + write(&g, move |g| { + tools::delete_block( + g, + &DeleteBlockParams { + block: jblock.to_string(), + }, + ) + }), + write(&g, |g| { + tools::set_page_tags( + g, + &SetPageTagsParams { + page: "2026-03-08".into(), + tags: Some(vec!["x".into()]), + ..Default::default() + }, + ) + }), + write(&g, |g| { + tools::create_page( + g, + &CreatePageParams { + title: "2026-04-01".into(), + ..Default::default() + }, + ) + }), + // Fails after creating the page (unknown hub is checked first; bad tag is not): + // the whole call must roll back. + write(&g, |g| { + tools::create_page( + g, + &CreatePageParams { + title: "Half done".into(), + tags: Some(vec!["x".repeat(500)]), + ..Default::default() + }, + ) + }), + write(&g, |g| { + tools::create_page( + g, + &CreatePageParams { + title: "From missing day".into(), + source_journal: Some("2026-03-09".into()), + ..Default::default() + }, + ) + }), + ] { + assert!(e.is_err(), "{e:?}"); + } + assert_eq!(g.last_seq().unwrap(), seq, "nothing written"); + assert!(g.page_by_title("Half done").unwrap().is_none()); +} + +#[test] +fn reads_are_rolled_back() { + let (_d, g) = fixture(); + let seq = g.last_seq().unwrap(); + // A read job that tries to write is undone. + let out = read(&g, |g| { + g.create_page(NewPage::titled("Sneaky"))?; + Ok("ok".into()) + }); + assert_eq!(out, "ok"); + assert_eq!(g.last_seq().unwrap(), seq); + assert!(g.page_by_title("Sneaky").unwrap().is_none()); +} + +#[test] +fn resources_render_pages() { + let (_d, g) = fixture(); + let out = read(&g, |g| tools::page_resource(g, "Dune")); + assert!(out.contains("- Arrakis is a desert planet\n"), "{out}"); +}