From c8f7cdaf923f50feba1a597206a63141282fe328 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:09:41 +0100 Subject: [PATCH 1/7] refactor(import): expose the Markdown outline parser The MCP server reuses it to turn Markdown outlines into nested blocks. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-import/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/synapse-import/src/lib.rs b/crates/synapse-import/src/lib.rs index 99b1eb5..d91d54c 100644 --- a/crates/synapse-import/src/lib.rs +++ b/crates/synapse-import/src/lib.rs @@ -7,7 +7,7 @@ mod config; mod names; -mod outline; +pub mod outline; mod rewrite; mod track; From c0f0716d3b1580f74359adb7bae63dca0adca5b4 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:09:41 +0100 Subject: [PATCH 2/7] feat(mcp): add synapse-mcp server with stdio binary Read tools (search, get_page, get_journal, list_pages, backlinks, related, list_tags, list_types, hubs, timeline, journal_links) and page-curation write tools behind --allow-write (create_page, append_blocks, update_block, delete_block, set_page_type, set_page_tags, set_page_hub). Journals are read-only. Reads run in a rolled-back transaction; writes in BEGIN IMMEDIATE through the Graph API so they are logged as ops and sync. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 158 ++++ crates/synapse-mcp/Cargo.toml | 31 + crates/synapse-mcp/src/lib.rs | 552 ++++++++++++ crates/synapse-mcp/src/main.rs | 80 ++ crates/synapse-mcp/src/params.rs | 236 +++++ crates/synapse-mcp/src/text.rs | 133 +++ crates/synapse-mcp/src/tools.rs | 1333 +++++++++++++++++++++++++++++ crates/synapse-mcp/tests/stdio.rs | 163 ++++ crates/synapse-mcp/tests/tools.rs | 622 ++++++++++++++ 9 files changed, 3308 insertions(+) create mode 100644 crates/synapse-mcp/Cargo.toml create mode 100644 crates/synapse-mcp/src/lib.rs create mode 100644 crates/synapse-mcp/src/main.rs create mode 100644 crates/synapse-mcp/src/params.rs create mode 100644 crates/synapse-mcp/src/text.rs create mode 100644 crates/synapse-mcp/src/tools.rs create mode 100644 crates/synapse-mcp/tests/stdio.rs create mode 100644 crates/synapse-mcp/tests/tools.rs 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}"); +} From 8459838d018a820225890db1d7d6f7e3c6381a3a Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:13:44 +0100 Subject: [PATCH 3/7] feat(server): serve MCP over Streamable HTTP at /v1/graphs/{id}/mcp Enabled by SYNAPSE_MCP_TOKEN (own bearer tokens, constant-time check), write tools with SYNAPSE_MCP_ALLOW_WRITE=1, Host allowlist via SYNAPSE_MCP_ALLOWED_HOSTS. Stateless JSON responses; tools run on the shared graph handle and wake SSE subscribers after writes. Never creates graphs. Co-Authored-By: Claude Opus 5.5 --- .env.example | 8 ++ Cargo.lock | 1 + crates/synapse-mcp/src/lib.rs | 2 + crates/synapse-server/Cargo.toml | 2 + crates/synapse-server/src/config.rs | 46 ++++++- crates/synapse-server/src/lib.rs | 15 ++- crates/synapse-server/src/mcp.rs | 106 ++++++++++++++++ crates/synapse-server/tests/e2e.rs | 1 + crates/synapse-server/tests/mcp.rs | 187 ++++++++++++++++++++++++++++ docs/server.md | 3 + 10 files changed, 367 insertions(+), 4 deletions(-) create mode 100644 crates/synapse-server/src/mcp.rs create mode 100644 crates/synapse-server/tests/mcp.rs diff --git a/.env.example b/.env.example index 1f01933..a4cbb19 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,14 @@ SYNAPSE_UPDATE_TOKEN= SYNAPSE_UPDATE_SCRIPT= # Reject pushed ops whose clock is more than this many minutes ahead of the server (default 10) SYNAPSE_MAX_CLOCK_SKEW_MINUTES= +# MCP endpoint (/v1/graphs/{id}/mcp) bearer token(s), comma separated, each >= 16 chars, +# separate from SYNAPSE_AUTH_TOKEN. MCP disabled if empty. See docs/mcp.md. +SYNAPSE_MCP_TOKEN= +# Set to 1 to expose the MCP write tools (page curation; journals stay read-only) +SYNAPSE_MCP_ALLOW_WRITE= +# Host headers the MCP endpoint accepts, comma separated (default localhost,127.0.0.1,::1; +# set your public hostname behind a proxy, or * for any) +SYNAPSE_MCP_ALLOWED_HOSTS= # Log format: text (default) or json SYNAPSE_LOG_FORMAT= # Log filter, e.g. info,synapse_server=debug diff --git a/Cargo.lock b/Cargo.lock index d353a8b..09b5753 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3508,6 +3508,7 @@ dependencies = [ "serde", "serde_json", "synapse-core", + "synapse-mcp", "synapse-sync", "tempfile", "tokio", diff --git a/crates/synapse-mcp/src/lib.rs b/crates/synapse-mcp/src/lib.rs index dc2775d..75cbe22 100644 --- a/crates/synapse-mcp/src/lib.rs +++ b/crates/synapse-mcp/src/lib.rs @@ -12,6 +12,8 @@ //! 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 use rmcp; + pub mod params; pub mod text; pub mod tools; diff --git a/crates/synapse-server/Cargo.toml b/crates/synapse-server/Cargo.toml index a3336fb..3bdcb9d 100644 --- a/crates/synapse-server/Cargo.toml +++ b/crates/synapse-server/Cargo.toml @@ -16,6 +16,8 @@ path = "src/main.rs" synapse-core.workspace = true # Shared wire types (single source of truth for the protocol). synapse-sync = { path = "../synapse-sync" } +# MCP tools and Streamable HTTP service mounted at /v1/graphs/{id}/mcp. +synapse-mcp = { path = "../synapse-mcp" } serde.workspace = true serde_json.workspace = true chrono.workspace = true diff --git a/crates/synapse-server/src/config.rs b/crates/synapse-server/src/config.rs index d4ee7d6..8c0c73a 100644 --- a/crates/synapse-server/src/config.rs +++ b/crates/synapse-server/src/config.rs @@ -13,10 +13,26 @@ pub struct Config { pub update_script: PathBuf, /// Ops whose HLC is further ahead of the server clock than this are rejected. pub max_clock_skew: Duration, + /// MCP endpoint (`/v1/graphs/{id}/mcp`); disabled when `None`. + pub mcp: Option, +} + +/// MCP over Streamable HTTP (`docs/mcp.md`). +#[derive(Debug, Clone)] +pub struct McpConfig { + /// Accepted bearer tokens (`SYNAPSE_MCP_TOKEN`, comma separated), separate from sync. + pub tokens: Vec, + /// Expose the write tools (`SYNAPSE_MCP_ALLOW_WRITE=1`). + pub allow_write: bool, + /// Accepted `Host` headers (`SYNAPSE_MCP_ALLOWED_HOSTS`); empty = any host. + pub allowed_hosts: Vec, } pub const MIN_TOKEN_LEN: usize = 16; +/// Loopback only, like the MCP SDK default (set `SYNAPSE_MCP_ALLOWED_HOSTS` behind a proxy). +pub const DEFAULT_MCP_HOSTS: [&str; 3] = ["localhost", "127.0.0.1", "::1"]; + impl Config { pub fn from_env() -> Result { let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); @@ -31,6 +47,22 @@ impl Config { .map(|t| t.trim().to_string()) .filter(|t| !t.is_empty()) .collect(); + let list = |v: String| -> Vec { + v.split(',') + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()) + .collect() + }; + let mcp = var("SYNAPSE_MCP_TOKEN").map(|t| McpConfig { + tokens: list(t), + allow_write: var("SYNAPSE_MCP_ALLOW_WRITE") + .is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes")), + allowed_hosts: match var("SYNAPSE_MCP_ALLOWED_HOSTS") { + Some(h) if h.trim() == "*" => Vec::new(), + Some(h) => list(h), + None => DEFAULT_MCP_HOSTS.iter().map(|h| h.to_string()).collect(), + }, + }); let cfg = Self { bind, data_dir: data_dir.into(), @@ -46,6 +78,7 @@ impl Config { .map_err(|e| format!("SYNAPSE_MAX_CLOCK_SKEW_MINUTES: {e}"))? .unwrap_or(10), ), + mcp, }; cfg.validate()?; Ok(cfg) @@ -55,7 +88,18 @@ impl Config { if self.auth_tokens.is_empty() { return Err("no auth token configured".into()); } - for t in self.auth_tokens.iter().chain(self.update_token.iter()) { + if let Some(m) = &self.mcp + && m.tokens.is_empty() + { + return Err("SYNAPSE_MCP_TOKEN has no token".into()); + } + let mcp_tokens = self.mcp.iter().flat_map(|m| m.tokens.iter()); + for t in self + .auth_tokens + .iter() + .chain(self.update_token.iter()) + .chain(mcp_tokens) + { if t.len() < MIN_TOKEN_LEN { return Err(format!( "tokens must be at least {MIN_TOKEN_LEN} characters" diff --git a/crates/synapse-server/src/lib.rs b/crates/synapse-server/src/lib.rs index 5d4c5e3..67480d4 100644 --- a/crates/synapse-server/src/lib.rs +++ b/crates/synapse-server/src/lib.rs @@ -7,6 +7,7 @@ mod blobs; pub mod config; mod error; mod graphs; +mod mcp; use axum::extract::DefaultBodyLimit; use axum::routing::{get, head, post}; @@ -29,6 +30,9 @@ pub struct AppState { pub(crate) updater: Arc, pub(crate) shutdown: Arc, pub(crate) max_clock_skew: std::time::Duration, + /// MCP endpoint state; `None` when `SYNAPSE_MCP_TOKEN` is unset. + pub(crate) mcp: Option>, + pub(crate) mcp_config: Option, } impl AppState { @@ -46,6 +50,8 @@ impl AppState { updater: Arc::new(admin::Updater::default()), shutdown: Arc::new(Notify::new()), max_clock_skew: cfg.max_clock_skew, + mcp: cfg.mcp.as_ref().map(|m| Arc::new(mcp::McpState::new(m))), + mcp_config: cfg.mcp.clone(), }) } } @@ -91,10 +97,13 @@ pub fn router(state: AppState) -> Router { admin::admin_guard, )); - Router::new() + let mut app = Router::new() .route("/healthz", get(healthz)) - .nest("/v1", graph_routes) - .nest("/admin", admin_routes) + .nest("/v1", graph_routes); + if let Some(cfg) = &state.mcp_config { + app = app.merge(mcp::routes(state.clone(), cfg)); + } + app.nest("/admin", admin_routes) .layer(TraceLayer::new_for_http()) .with_state(state) } diff --git a/crates/synapse-server/src/mcp.rs b/crates/synapse-server/src/mcp.rs new file mode 100644 index 0000000..cf31b55 --- /dev/null +++ b/crates/synapse-server/src/mcp.rs @@ -0,0 +1,106 @@ +//! MCP over Streamable HTTP at `/v1/graphs/{id}/mcp` (`docs/mcp.md`). +//! +//! Its own bearer tokens (`SYNAPSE_MCP_TOKEN`), checked here; the graph must already exist +//! (MCP never creates one). Tools run on the server's shared graph handle, so writes are +//! normal ops: they are logged, pushed to SSE subscribers and pulled by every client. + +use crate::AppState; +use crate::auth::{Authenticator, bearer}; +use crate::config::McpConfig; +use crate::error::ApiError; +use crate::graphs::GraphHandle; +use axum::Router; +use axum::extract::{Path, Request, State}; +use axum::http::StatusCode; +use axum::middleware::{self, Next}; +use axum::response::Response; +use std::sync::Arc; +use synapse_mcp::rmcp::transport::streamable_http_server::session::never::NeverSessionManager; +use synapse_mcp::rmcp::transport::streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, +}; +use synapse_mcp::tools::ToolError; +use synapse_mcp::{GraphHost, HostFuture, HostRef, Job, SynapseMcp}; + +pub struct McpState { + auth: Authenticator, +} + +impl McpState { + pub fn new(cfg: &McpConfig) -> Self { + Self { + auth: Authenticator::from_shared_tokens(&cfg.tokens), + } + } +} + +/// Runs tool jobs on a server graph and wakes SSE subscribers after writes. +struct ServerHost(Arc); + +impl GraphHost for ServerHost { + fn run(&self, job: Job) -> HostFuture { + let h = self.0.clone(); + Box::pin(async move { + let (out, seq) = h + .run(move |g| Ok((job(g), g.last_seq()))) + .await + .map_err(|e| ToolError::new(e.message))?; + if let Ok(seq) = seq { + h.publish_seq(seq); + } + out + }) + } +} + +/// Authenticates, resolves the graph and hands it to the MCP service via an extension. +async fn guard( + State(s): State, + Path(id): Path, + mut req: Request, + next: Next, +) -> Result { + let mcp = s + .mcp + .as_ref() + .ok_or_else(|| ApiError::not_found("not found"))?; + let who = bearer(&req) + .and_then(|t| mcp.auth.authenticate(t)) + .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "missing or invalid token"))?; + if !who.can_access(&id) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "no access to this graph", + )); + } + let handle = s + .graphs + .get(&id) + .await? + .ok_or_else(|| ApiError::not_found("graph not found"))?; + req.extensions_mut() + .insert(HostRef(Arc::new(ServerHost(handle)))); + Ok(next.run(req).await) +} + +pub fn routes(state: AppState, cfg: &McpConfig) -> Router { + let proto = SynapseMcp::new(None, cfg.allow_write); + let mut http = StreamableHttpServerConfig::default() + // Stateless request/response: no sessions to keep, JSON replies. + .with_legacy_session_mode(false) + .with_json_response(true) + .with_sse_keep_alive(None); + http = if cfg.allowed_hosts.is_empty() { + http.disable_allowed_hosts() + } else { + http.with_allowed_hosts(cfg.allowed_hosts.clone()) + }; + let service = StreamableHttpService::new( + move || Ok(proto.clone()), + Arc::new(NeverSessionManager::default()), + http, + ); + Router::new() + .route_service("/v1/graphs/{id}/mcp", service) + .route_layer(middleware::from_fn_with_state(state, guard)) +} diff --git a/crates/synapse-server/tests/e2e.rs b/crates/synapse-server/tests/e2e.rs index 099bb05..ea925dd 100644 --- a/crates/synapse-server/tests/e2e.rs +++ b/crates/synapse-server/tests/e2e.rs @@ -23,6 +23,7 @@ impl TestServer { update_token: None, update_script: "/nonexistent".into(), max_clock_skew: Duration::from_secs(600), + mcp: None, }; let server = synapse_server::start(&cfg).await.unwrap(); Self { server, _dir: dir } diff --git a/crates/synapse-server/tests/mcp.rs b/crates/synapse-server/tests/mcp.rs new file mode 100644 index 0000000..7d1ab2b --- /dev/null +++ b/crates/synapse-server/tests/mcp.rs @@ -0,0 +1,187 @@ +//! MCP over Streamable HTTP: auth, tool calls, read-only vs write. + +use serde_json::{Value, json}; +use std::time::Duration; +use synapse_core::{Graph, NewPage, Placement}; +use synapse_server::config::{DEFAULT_MCP_HOSTS, McpConfig}; +use synapse_server::{Config, RunningServer}; + +const SYNC_TOKEN: &str = "sync-token-0123456789abcdef"; +const MCP_TOKEN: &str = "mcp-token-0123456789abcdef"; + +async fn start(dir: &std::path::Path, allow_write: bool) -> RunningServer { + let cfg = Config { + bind: "127.0.0.1:0".parse().unwrap(), + data_dir: dir.join("data"), + auth_tokens: vec![SYNC_TOKEN.into()], + update_token: None, + update_script: "/nonexistent".into(), + max_clock_skew: Duration::from_secs(600), + mcp: Some(McpConfig { + tokens: vec![MCP_TOKEN.into()], + allow_write, + allowed_hosts: DEFAULT_MCP_HOSTS.iter().map(|h| h.to_string()).collect(), + }), + }; + cfg.validate().unwrap(); + synapse_server::start(&cfg).await.unwrap() +} + +fn seed(dir: &std::path::Path) { + let g = Graph::open(dir.join("data").join("main")).unwrap(); + let p = g.create_page(NewPage::titled("Rust")).unwrap(); + g.insert_block( + p.id, + Placement::LastChildOf(None), + "ownership and borrowing", + ) + .unwrap(); +} + +async fn rpc( + srv: &RunningServer, + graph: &str, + token: Option<&str>, + method: &str, + params: Value, +) -> (u16, Value) { + let mut req = reqwest::Client::new() + .post(format!("http://{}/v1/graphs/{graph}/mcp", srv.addr)) + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", "2025-06-18") + .json(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})); + if let Some(t) = token { + req = req.bearer_auth(t); + } + let res = req.send().await.unwrap(); + let status = res.status().as_u16(); + let body = res.text().await.unwrap(); + (status, serde_json::from_str(&body).unwrap_or(json!(body))) +} + +fn init_params() -> Value { + json!({"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "test", "version": "1"}}) +} + +fn tool_names(v: &Value) -> Vec { + v["result"]["tools"] + .as_array() + .unwrap_or_else(|| panic!("{v}")) + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn mcp_requires_its_own_token_and_an_existing_graph() { + let dir = tempfile::tempdir().unwrap(); + seed(dir.path()); + let srv = start(dir.path(), false).await; + for token in [None, Some("wrong-token-0123456789"), Some(SYNC_TOKEN)] { + let (status, _) = rpc(&srv, "main", token, "initialize", init_params()).await; + assert_eq!(status, 401, "token {token:?}"); + } + let (status, _) = rpc(&srv, "nope", Some(MCP_TOKEN), "initialize", init_params()).await; + assert_eq!(status, 404); + assert!(!dir.path().join("data").join("nope").exists()); + // The sync API does not accept the MCP token either. + let res = reqwest::Client::new() + .get(format!("http://{}/v1/graphs/main/pages", srv.addr)) + .bearer_auth(MCP_TOKEN) + .send() + .await + .unwrap(); + assert_eq!(res.status().as_u16(), 401); + // DNS-rebinding guard: a foreign Host header is refused even with a valid token. + let res = reqwest::Client::new() + .post(format!("http://{}/v1/graphs/main/mcp", srv.addr)) + .header("host", "evil.example.com") + .header("accept", "application/json, text/event-stream") + .bearer_auth(MCP_TOKEN) + .json(&json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": init_params()})) + .send() + .await + .unwrap(); + assert!(res.status().is_client_error(), "{}", res.status()); + srv.shutdown(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn read_only_server_hides_write_tools() { + let dir = tempfile::tempdir().unwrap(); + seed(dir.path()); + let srv = start(dir.path(), false).await; + let (status, init) = rpc(&srv, "main", Some(MCP_TOKEN), "initialize", init_params()).await; + assert_eq!(status, 200, "{init}"); + assert_eq!(init["result"]["serverInfo"]["name"], "synapse-mcp"); + let (_, list) = rpc(&srv, "main", Some(MCP_TOKEN), "tools/list", json!({})).await; + let names = tool_names(&list); + assert!(names.contains(&"search".to_string()), "{names:?}"); + assert!(!names.iter().any(|n| n == "create_page"), "{names:?}"); + let (_, r) = rpc( + &srv, + "main", + Some(MCP_TOKEN), + "tools/call", + json!({"name": "search", "arguments": {"query": "borrowing"}}), + ) + .await; + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("[[Rust]]"), "{r}"); + let (_, r) = rpc( + &srv, + "main", + Some(MCP_TOKEN), + "tools/call", + json!({"name": "create_page", "arguments": {"title": "X"}}), + ) + .await; + assert!( + r.get("error").is_some() || r["result"]["isError"] == json!(true), + "{r}" + ); + srv.shutdown(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn writes_go_through_the_op_log() { + let dir = tempfile::tempdir().unwrap(); + seed(dir.path()); + let srv = start(dir.path(), true).await; + let (_, list) = rpc(&srv, "main", Some(MCP_TOKEN), "tools/list", json!({})).await; + assert!(tool_names(&list).contains(&"create_page".to_string())); + let (_, r) = rpc( + &srv, + "main", + Some(MCP_TOKEN), + "tools/call", + json!({"name": "create_page", + "arguments": {"title": "Borrow checker", "type": "Concept", + "content": "- rejects aliasing + mutation"}}), + ) + .await; + assert_eq!(r["result"]["isError"], json!(false), "{r}"); + // Visible through the sync API (same graph handle, logged as ops). + let res = reqwest::Client::new() + .get(format!( + "http://{}/v1/graphs/main/pages/by-title?title=borrow%20checker", + srv.addr + )) + .bearer_auth(SYNC_TOKEN) + .send() + .await + .unwrap(); + assert_eq!(res.status().as_u16(), 200); + let ops: Value = reqwest::Client::new() + .get(format!("http://{}/v1/graphs/main/ops?since=0", srv.addr)) + .bearer_auth(SYNC_TOKEN) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!(ops.to_string().contains("rejects aliasing"), "{ops}"); + srv.shutdown(); +} diff --git a/docs/server.md b/docs/server.md index 1f59404..fe7c404 100644 --- a/docs/server.md +++ b/docs/server.md @@ -15,6 +15,9 @@ See `.env.example`. | `SYNAPSE_MAX_CLOCK_SKEW_MINUTES` | no | Reject pushed ops whose HLC is further ahead of the server clock (default 10) | | `SYNAPSE_UPDATE_TOKEN` | no | Enables `/admin/update`; separate from the sync tokens | | `SYNAPSE_UPDATE_SCRIPT` | no | Default `/opt/synapse/scripts/update.sh` | +| `SYNAPSE_MCP_TOKEN` | no | Enables MCP at `/v1/graphs/{id}/mcp` (`docs/mcp.md`). Own token(s), comma separated, ≥ 16 chars | +| `SYNAPSE_MCP_ALLOW_WRITE` | no | `1` exposes the MCP write tools (page curation; journals stay read-only) | +| `SYNAPSE_MCP_ALLOWED_HOSTS` | no | `Host` headers MCP accepts; default loopback only. Set the public hostname behind a proxy (`*` = any) | | `SYNAPSE_LOG_FORMAT` | no | `text` (default) or `json` | | `RUST_LOG` | no | Log filter, default `info` | From 0253cd418042a84fffd9d598769d9c0a13503b0d Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:14:27 +0100 Subject: [PATCH 4/7] docs(mcp): document the MCP server, setup and tools Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++ README.md | 3 +- docs/README.md | 1 + docs/architecture.md | 2 + docs/mcp.md | 114 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 docs/mcp.md diff --git a/CLAUDE.md b/CLAUDE.md index 29f36e6..6be5d9e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,8 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client (`flutter analyze` crashes on non-ASCII paths like `Darío/`) - Test: `cargo test --workspace`, `cd app && flutter test` - Run server: `SYNAPSE_DATA_DIR=/tmp/syn SYNAPSE_AUTH_TOKEN=<16+ chars> cargo run -p synapse-server` + (add `SYNAPSE_MCP_TOKEN=<16+ chars>` for MCP at `/v1/graphs/{id}/mcp`) +- Run MCP (stdio): `cargo run -p synapse-mcp -- --graph [--allow-write]` - Run app: `cd app && flutter run -d linux` (or `-d windows`, an Android device); Flutter SDK in `~/development/flutter/bin`. Graph dir override: `SYNAPSE_GRAPH=/path`. See `docs/app.md`. - Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` (frb 2.13.0; commit @@ -27,6 +29,7 @@ roadmap in `docs/plan.md`. - `synapse-history`: automatic git-like snapshots of the graph. - `synapse-caldav`: CalDAV calendar + VTODO tasks. - `synapse-sync` / `synapse-server`: client-server protocol and axum server (`docs/sync.md`). +- `synapse-mcp`: MCP tools for AI assistants; stdio binary + HTTP service (`docs/mcp.md`). - `synapse-ffi`: the only API surface exposed to Flutter. ## Conventions diff --git a/README.md b/README.md index d33881f..06aa518 100644 --- a/README.md +++ b/README.md @@ -13,4 +13,5 @@ cargo test --workspace cd app && flutter run -d linux ``` -See [docs/](docs/README.md) for the plan and architecture. +See [docs/](docs/README.md) for the plan and architecture, and [docs/mcp.md](docs/mcp.md) to +connect AI assistants (MCP). diff --git a/docs/README.md b/docs/README.md index e9fb086..54570e7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,3 +9,4 @@ - [history.md](history.md): automatic git snapshots and restore. - [caldav.md](caldav.md): CalDAV calendars and tasks. - [server.md](server.md): running and deploying the sync server. +- [mcp.md](mcp.md): MCP server for AI assistants (stdio and HTTP), tools, security. diff --git a/docs/architecture.md b/docs/architecture.md index c75bd99..fa3c29a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,6 +6,8 @@ app/ (Flutter, Dart) ──FFI──▶ synapse-ffi ──▶ synapse-core │ │ └─────── synapse-history ├──▶ synapse-ai ──┘ (Embedder) synapse-caldav └──▶ synapse-sync ──HTTP──▶ synapse-server (axum) +AI assistant ──MCP stdio──▶ synapse-mcp ──▶ synapse-core │ +AI assistant ──MCP HTTP───────────────────▶ /v1/graphs/{id}/mcp ┘ (synapse-mcp tools) ``` ## Graph on disk diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..b381114 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,114 @@ +# MCP server + +`synapse-mcp` lets AI assistants (Claude Code, Claude Desktop, any MCP client) read a graph +and curate its pages through high-level tools: no SQL, no file access. Two transports share +the same tools (`crates/synapse-mcp`, built on the official Rust SDK `rmcp`): + +- **stdio**: the `synapse-mcp` binary on a local graph directory, next to the running app. +- **Streamable HTTP**: mounted in `synapse-server` at `/v1/graphs/{id}/mcp`. + +## Intended workflow +The journal is the input; pages are the output. The assistant reads recent journals +(`get_journal`, `journal_links`, `timeline`), then creates pages for things mentioned there +(`create_page`, with `source_journal` to record the day they come from), types, tags and files +them in hubs reusing the existing vocabulary (`list_types`, `list_tags`, `hubs`), and fills +untyped/untagged pages (`list_pages` with `untyped` / `untagged`). **Journals are read-only +through MCP**: every write tool refuses journal pages and blocks. + +## Setup +### stdio (local graph) +```bash +cargo build --release -p synapse-mcp # target/release/synapse-mcp +synapse-mcp --graph ~/synapse # read-only +synapse-mcp --graph ~/synapse --allow-write +``` +Without `--graph` it uses `$SYNAPSE_GRAPH`, else the app's directory +(`~/.local/share/dev.dasemu.synapse/graph` on Linux, `%APPDATA%\dasemu\Synapse\graph` on +Windows). It refuses a directory without `synapse.db` (it never creates a graph). + +Claude Code: +```bash +claude mcp add synapse -- /path/to/synapse-mcp --graph /path/to/graph +``` +Claude Desktop (`claude_desktop_config.json`): +```json +{ "mcpServers": { "synapse": { + "command": "/path/to/synapse-mcp", "args": ["--graph", "/path/to/graph"] } } } +``` + +### HTTP (sync server) +Set `SYNAPSE_MCP_TOKEN` (own tokens, comma separated, ≥ 16 chars, never the sync token) and, +behind a proxy, `SYNAPSE_MCP_ALLOWED_HOSTS=notes.example.com`. Add +`SYNAPSE_MCP_ALLOW_WRITE=1` for the write tools. See `docs/server.md`. The graph must already +exist on the server (created by a syncing client). + +Claude Code: +```bash +claude mcp add --transport http synapse https://notes.example.com/v1/graphs//mcp \ + --header "Authorization: Bearer $SYNAPSE_MCP_TOKEN" +``` +Claude Desktop: use a remote connector with that URL and header, or bridge it with +`npx mcp-remote --header "Authorization: Bearer "`. + +## Tools +Outputs are compact Markdown: `[[Page]]` titles, `((block-id))` after each block (its own id, +needed by the block tools), cursors (`next cursor: N`) for long lists. Pages are addressed by +title, alias, id or journal date (`YYYY-MM-DD`, `today`, `yesterday`). Errors come back as +tool errors with a hint (e.g. "did you mean [[Dune]]?"). + +| Tool | What | +|---|---| +| `search` | Titles/aliases + block text; all words must match, case/accent-insensitive, `"phrases"`. Filters: `scope`, `journals`, `tag`, `type`, `hub`, `page`, `from`/`to` | +| `get_page` | Header (type, tags, hub, aliases, properties, dates, born-in journal) + outline; `block` subtree, `max_depth`, `ids`, cursor. Hubs list members | +| `get_journal` | One day or a `from`/`to` range (≤ 31 days). Never creates a journal | +| `list_pages` | Filters `type`, `tag`, `hub`, `untyped`, `untagged`, `updated_since`, `created_since`, `journals`; sort `updated`/`created`/`title` | +| `backlinks` | Linked references grouped by page, parent block as context | +| `related` | Spreading activation (`Graph::related`) | +| `list_tags` / `list_types` | Vocabulary with counts (types: icons, unused defined/suggested) | +| `hubs` | Hub tree with note counts, or one hub's members | +| `timeline` | Per day (≤ 92 days): journal, pages born, pages edited | +| `journal_links` | Per journal day: linked pages with status (type, tags, untyped, untagged, empty) and existing pages mentioned without a link | + +Write tools (only with `--allow-write` / `SYNAPSE_MCP_ALLOW_WRITE=1`; otherwise not listed): + +| Tool | What | +|---|---| +| `create_page` | Title, `type`, `tags`, `hub`, Markdown outline `content`, `source_journal` (existing day; the page is "born" there) | +| `append_blocks` | Markdown outline at the end of a page or under a `parent` block | +| `update_block` / `delete_block` | Replace a block's text / delete it with its children | +| `set_page_type` | Set or clear (null) the single type | +| `set_page_tags` | `tags` replaces; `add` / `remove` edit | +| `set_page_hub` | Move into a hub, or out with null | + +Markdown outlines use `- ` bullets with 2-space indents; `key:: value` lines are block +properties (leading ones are page properties); plain paragraphs become top-level blocks. +Resources: `synapse://page/{title}` and `synapse://journal/{date}` (outline without ids). + +## Design decisions +- **SDK**: `rmcp` (official) covers both transports, tool schemas from the parameter structs + (`schemars`) and protocol negotiation; hand-rolling JSON-RPC would duplicate all of that. +- **Concurrency (stdio)**: the graph is opened per call (`LocalHost`) next to the app (SQLite + WAL). Reads run in a deferred transaction that is always rolled back (a consistent snapshot + that can never write); writes run in `BEGIN IMMEDIATE`, held only for the call, retried a few + times while SQLite is busy (plus the 5 s busy timeout). Opening per call also re-reads the + op log's last clock, so this process never stamps ops behind the app's. +- **Server**: tools run on the shared graph handle (`GraphHandle::run`), so writes are normal + ops: logged, pushed to SSE subscribers, pulled by every client. Stateless JSON responses (no + MCP sessions to keep). +- **Search** is a scan of the core `pages`/`blocks`/`aliases` tables, not the tantivy index of + `synapse-search`: the app does not maintain that index yet, and a second process owning its + writer lock would block the app once it does. Fine for personal graphs (tens of thousands + of blocks); switch to a read-only tantivy reader when the app indexes. +- **Writes** use only the `Graph` API (`create_page`, `insert_block`, `set_page_type`, ...). + Side effects inherited from the core: a page born today, or edited today, ensures today's + (empty) journal page exists, and `[[New Page]]` links create those pages, as in the app. + The journal content itself is never modified. `rename_page` is not exposed: it rewrites the + links in every referencing block, journals included. + +## Security +- The assistant sees everything the tools return, including any secret written in plain text + in a note. Only connect assistants you trust with the whole graph. +- Only core page/block data is exposed: no module data, no settings, no raw tables. +- HTTP: own tokens (hashed, constant-time compare), separate from the sync tokens; the graph + must exist; `Host` allowlist against DNS rebinding; always behind TLS (see `server.md`). +- Read-only by default on both transports; write tools are not even listed without the flag. From 4195374c230ded7bbe59ed786965c7d545cbfc17 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:22:14 +0100 Subject: [PATCH 5/7] fix(mcp): harden stdio opens, commits and user-supplied ranges - Check per call that synapse.db exists and is on this binary's schema, so the stdio server never migrates or re-stamps the app's live database. - Keep the transaction open (rolled back on drop) when COMMIT fails. - Reject dates outside years 1000-9999 and oversized cursors (overflow). - core: export SCHEMA_VERSION. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/lib.rs | 1 + crates/synapse-mcp/src/lib.rs | 47 +++++++++++++++++++++++++++++-- crates/synapse-mcp/src/tools.rs | 13 +++++++-- crates/synapse-mcp/tests/stdio.rs | 33 ++++++++++++++++++++++ crates/synapse-mcp/tests/tools.rs | 25 ++++++++++++++++ 5 files changed, 115 insertions(+), 4 deletions(-) diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 77d1947..afb0185 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -20,6 +20,7 @@ pub mod types; pub use error::{Error, Result}; pub use model::*; +pub use schema::VERSION as SCHEMA_VERSION; pub use store::Graph; pub use structure::{ HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent, diff --git a/crates/synapse-mcp/src/lib.rs b/crates/synapse-mcp/src/lib.rs index 75cbe22..a1fa86e 100644 --- a/crates/synapse-mcp/src/lib.rs +++ b/crates/synapse-mcp/src/lib.rs @@ -75,7 +75,7 @@ impl GraphHost for LocalHost { let dir = self.dir.clone(); Box::pin(async move { tokio::task::spawn_blocking(move || { - let g = Graph::open(&dir).map_err(ToolError::from)?; + let g = open_local(&dir)?; job(&g) }) .await @@ -84,6 +84,48 @@ impl GraphHost for LocalHost { } } +/// Opens the app's graph without surprises: it must still exist (never re-created) and be +/// on this binary's schema (`Graph::open` would migrate or re-stamp a live database). +fn open_local(dir: &std::path::Path) -> Result { + let db = dir.join("synapse.db"); + if !db.is_file() { + return Err(ToolError::new(format!("graph {} is gone", dir.display()))); + } + let schema: Option = { + let conn = rusqlite::Connection::open_with_flags( + &db, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + )?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + conn.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| { + r.get::<_, String>(0) + }) + .ok() + }; + let want = synapse_core::SCHEMA_VERSION.to_string(); + if schema.as_deref() != Some(want.as_str()) { + return Err(ToolError::new(format!( + "graph schema is v{} but this synapse-mcp expects v{want}; use a synapse-mcp built \ + from the same version as the app", + schema.as_deref().unwrap_or("?") + ))); + } + with_retry_open(|| Graph::open(dir).map_err(ToolError::from)) +} + +fn with_retry_open(f: impl Fn() -> Result) -> Result { + let mut attempt = 0; + loop { + match f() { + 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, + } + } +} + /// Rolls back on drop unless committed. struct Txn<'a> { g: &'a Graph, @@ -96,8 +138,9 @@ impl<'a> Txn<'a> { Ok(Self { g, open: true }) } fn commit(mut self) -> Result<(), ToolError> { - self.open = false; + // On failure `open` stays true and Drop rolls back, so no transaction leaks. self.g.conn().execute_batch("COMMIT")?; + self.open = false; Ok(()) } } diff --git a/crates/synapse-mcp/src/tools.rs b/crates/synapse-mcp/src/tools.rs index 37827f8..f4a1d3b 100644 --- a/crates/synapse-mcp/src/tools.rs +++ b/crates/synapse-mcp/src/tools.rs @@ -69,6 +69,8 @@ impl From for ToolError { pub type ToolResult = Result; const MAX_RANGE_DAYS: i64 = 31; +/// Cursors are offsets; capped so offset arithmetic cannot overflow. +const MAX_CURSOR: usize = 1 << 32; const MAX_TIMELINE_DAYS: i64 = 92; // ------------------------------------------------------------------ helpers @@ -98,7 +100,10 @@ pub fn parse_date(g: &Graph, s: &str) -> Result { "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\""))), + .ok() + // Sane years only: date arithmetic near chrono's limits would overflow. + .filter(|d| (1000..=9999).contains(&chrono::Datelike::year(d))) + .ok_or_else(|| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))), } } @@ -131,7 +136,11 @@ fn date_range( 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:?}"))), + Some(c) => c + .parse::() + .ok() + .filter(|n| *n <= MAX_CURSOR) + .ok_or_else(|| err(format!("bad cursor {c:?}"))), } } diff --git a/crates/synapse-mcp/tests/stdio.rs b/crates/synapse-mcp/tests/stdio.rs index 87b8c30..07614b4 100644 --- a/crates/synapse-mcp/tests/stdio.rs +++ b/crates/synapse-mcp/tests/stdio.rs @@ -161,3 +161,36 @@ fn refuses_a_missing_graph() { assert!(!out.status.success()); assert!(!dir.path().join("nope").exists(), "must not create a graph"); } + +#[test] +fn refuses_a_graph_on_another_schema() { + let dir = tempfile::tempdir().unwrap(); + { + let g = Graph::open(dir.path()).unwrap(); + g.conn() + .execute("UPDATE meta SET value='1' WHERE key='schema'", []) + .unwrap(); + } + let mut s = Server::start(dir.path(), &[]); + s.init(); + let r = s.call( + 2, + "tools/call", + json!({"name": "list_pages", "arguments": {}}), + ); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("schema is v1"), "{r}"); + drop(s); + let g = Graph::open(dir.path()).unwrap(); + let v: String = g + .conn() + .query_row("SELECT value FROM meta WHERE key='schema'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!( + v, + synapse_core::SCHEMA_VERSION.to_string(), + "re-opened by core only here" + ); +} diff --git a/crates/synapse-mcp/tests/tools.rs b/crates/synapse-mcp/tests/tools.rs index d755dc9..a721fc7 100644 --- a/crates/synapse-mcp/tests/tools.rs +++ b/crates/synapse-mcp/tests/tools.rs @@ -620,3 +620,28 @@ fn resources_render_pages() { let out = read(&g, |g| tools::page_resource(g, "Dune")); assert!(out.contains("- Arrakis is a desert planet\n"), "{out}"); } + +#[test] +fn extreme_dates_and_cursors_are_rejected() { + let (_d, g) = fixture(); + let e = read_err(&g, |g| { + tools::timeline( + g, + &RangeParams { + from: None, + to: Some("-262143-01-03".into()), + }, + ) + }); + assert!(e.contains("bad date"), "{e}"); + let e = read_err(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + cursor: Some(usize::MAX.to_string()), + ..Default::default() + }, + ) + }); + assert!(e.contains("bad cursor"), "{e}"); +} From 053d1f9d9070645eb0fc1c0a2d352b6a2a13310b Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:22:14 +0100 Subject: [PATCH 6/7] fix(server): refuse an MCP token equal to a sync token Co-Authored-By: Claude Opus 5.5 --- crates/synapse-server/src/config.rs | 5 +++++ crates/synapse-server/tests/mcp.rs | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/synapse-server/src/config.rs b/crates/synapse-server/src/config.rs index 8c0c73a..983c5cd 100644 --- a/crates/synapse-server/src/config.rs +++ b/crates/synapse-server/src/config.rs @@ -93,6 +93,11 @@ impl Config { { return Err("SYNAPSE_MCP_TOKEN has no token".into()); } + if let Some(m) = &self.mcp + && m.tokens.iter().any(|t| self.auth_tokens.contains(t)) + { + return Err("SYNAPSE_MCP_TOKEN must differ from the sync tokens".into()); + } let mcp_tokens = self.mcp.iter().flat_map(|m| m.tokens.iter()); for t in self .auth_tokens diff --git a/crates/synapse-server/tests/mcp.rs b/crates/synapse-server/tests/mcp.rs index 7d1ab2b..72166d0 100644 --- a/crates/synapse-server/tests/mcp.rs +++ b/crates/synapse-server/tests/mcp.rs @@ -185,3 +185,21 @@ async fn writes_go_through_the_op_log() { assert!(ops.to_string().contains("rejects aliasing"), "{ops}"); srv.shutdown(); } + +#[test] +fn mcp_token_must_differ_from_sync_tokens() { + let cfg = Config { + bind: "127.0.0.1:0".parse().unwrap(), + data_dir: "/tmp/unused".into(), + auth_tokens: vec![SYNC_TOKEN.into()], + update_token: None, + update_script: "/nonexistent".into(), + max_clock_skew: Duration::from_secs(600), + mcp: Some(McpConfig { + tokens: vec![SYNC_TOKEN.into()], + allow_write: false, + allowed_hosts: Vec::new(), + }), + }; + assert!(cfg.validate().is_err()); +} From f8fe17b50f04f09aae2a91f15fb68282cc399765 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:22:14 +0100 Subject: [PATCH 7/7] docs(mcp): document journal side effects, schema check and known limits Co-Authored-By: Claude Opus 5.5 --- docs/mcp.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b381114..7326b38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -91,7 +91,9 @@ Resources: `synapse://page/{title}` and `synapse://journal/{date}` (outline with WAL). Reads run in a deferred transaction that is always rolled back (a consistent snapshot that can never write); writes run in `BEGIN IMMEDIATE`, held only for the call, retried a few times while SQLite is busy (plus the 5 s busy timeout). Opening per call also re-reads the - op log's last clock, so this process never stamps ops behind the app's. + op log's last clock. Each call checks that `synapse.db` still exists and is on this binary's + schema version, so the server never migrates or re-stamps the app's live database: build + `synapse-mcp` from the same version as the app. - **Server**: tools run on the shared graph handle (`GraphHandle::run`), so writes are normal ops: logged, pushed to SSE subscribers, pulled by every client. Stateless JSON responses (no MCP sessions to keep). @@ -101,8 +103,9 @@ Resources: `synapse://page/{title}` and `synapse://journal/{date}` (outline with of blocks); switch to a read-only tantivy reader when the app indexes. - **Writes** use only the `Graph` API (`create_page`, `insert_block`, `set_page_type`, ...). Side effects inherited from the core: a page born today, or edited today, ensures today's - (empty) journal page exists, and `[[New Page]]` links create those pages, as in the app. - The journal content itself is never modified. `rename_page` is not exposed: it rewrites the + journal page exists (empty if new; on the server "today" is the server's local date), and + links in written content create their target pages, `[[YYYY-MM-DD]]` included (an empty + journal), as in the app. Existing journal content is never modified. `rename_page` is not exposed: it rewrites the links in every referencing block, journals included. ## Security @@ -112,3 +115,11 @@ Resources: `synapse://page/{title}` and `synapse://journal/{date}` (outline with - HTTP: own tokens (hashed, constant-time compare), separate from the sync tokens; the graph must exist; `Host` allowlist against DNS rebinding; always behind TLS (see `server.md`). - Read-only by default on both transports; write tools are not even listed without the flag. +- Every MCP token reaches every graph on the server (no per-graph scoping yet). + +## Known limits +- The stdio server writes with the app's actor id. Its clock starts from the newest op, but the + running app's in-memory clock does not see MCP's ops, so in rare cases (same millisecond, or + a clock pinned ahead by a remote op) both can stamp an op with the same HLC; replicas could + then disagree on which edit of the same block wins. A core fix (re-observe the newest op + before ticking) is pending.