mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
c8f7cdaf92
commit
c0f0716d3b
9 files changed
+3308
No files matched your search
Generated
+158
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
@@ -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<dyn Fn(&Graph) -> ToolResult + Send + Sync + 'static>;
|
||||
pub type HostFuture = Pin<Box<dyn Future<Output = ToolResult> + 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<dyn GraphHost>);
|
||||
|
||||
/// 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<PathBuf>) -> std::io::Result<Self> {
|
||||
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<Self, ToolError> {
|
||||
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<Arc<dyn GraphHost>>,
|
||||
allow_write: bool,
|
||||
tool_router: ToolRouter<Self>,
|
||||
}
|
||||
|
||||
fn reply(r: ToolResult) -> Result<CallToolResult, ErrorData> {
|
||||
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<Arc<dyn GraphHost>>, 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<RoleServer>) -> Result<Arc<dyn GraphHost>, ToolError> {
|
||||
if let Some(h) = &self.host {
|
||||
return Ok(h.clone());
|
||||
}
|
||||
ctx.extensions
|
||||
.get::<http::request::Parts>()
|
||||
.and_then(|p| p.extensions.get::<HostRef>())
|
||||
.map(|h| h.0.clone())
|
||||
.ok_or_else(|| ToolError::new("no graph bound to this request"))
|
||||
}
|
||||
|
||||
async fn read(
|
||||
&self,
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
reply(match self.host_for(ctx) {
|
||||
Ok(h) => h.run(read_job(f)).await,
|
||||
Err(e) => Err(e),
|
||||
})
|
||||
}
|
||||
|
||||
async fn write(
|
||||
&self,
|
||||
ctx: &RequestContext<RoleServer>,
|
||||
f: impl Fn(&Graph) -> ToolResult + Send + Sync + 'static,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<SearchParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<GetPageParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<GetJournalParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<ListPagesParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<PageRefParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<PageRefParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<ListParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<ListParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<HubsParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<RangeParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<RangeParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<CreatePageParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<AppendBlocksParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<UpdateBlockParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<DeleteBlockParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<SetPageTypeParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<SetPageTagsParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<SetPageHubParams>,
|
||||
ctx: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
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<PaginatedRequestParams>,
|
||||
_ctx: RequestContext<RoleServer>,
|
||||
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
||||
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<RoleServer>,
|
||||
) -> Result<ReadResourceResponse, ErrorData> {
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! `synapse-mcp`: MCP server over stdio for a local Synapse graph.
|
||||
//!
|
||||
//! Usage: `synapse-mcp [--graph <dir>] [--allow-write]`. The graph defaults to
|
||||
//! `$SYNAPSE_GRAPH`, else the app's own location (`<app support dir>/graph`).
|
||||
|
||||
use rmcp::ServiceExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use synapse_mcp::{LocalHost, SynapseMcp};
|
||||
|
||||
const USAGE: &str = "usage: synapse-mcp [--graph <dir>] [--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<PathBuf> {
|
||||
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<PathBuf> = 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 <dir>"));
|
||||
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}"));
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// Journals: "any" (default), "only" or "exclude".
|
||||
#[serde(default)]
|
||||
pub journals: Option<String>,
|
||||
/// Only pages carrying this tag (explicit, implied by their type or by their hub).
|
||||
#[serde(default)]
|
||||
pub tag: Option<String>,
|
||||
/// Only pages of this type.
|
||||
#[serde(default, rename = "type")]
|
||||
pub page_type: Option<String>,
|
||||
/// Only direct members of this hub (title).
|
||||
#[serde(default)]
|
||||
pub hub: Option<String>,
|
||||
/// Only one page (title, alias, id or journal date).
|
||||
#[serde(default)]
|
||||
pub page: Option<String>,
|
||||
/// From date (YYYY-MM-DD, inclusive): journal date for journals, last edit for the rest.
|
||||
#[serde(default)]
|
||||
pub from: Option<String>,
|
||||
/// To date (YYYY-MM-DD, inclusive).
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
/// Max results (default 20, max 100).
|
||||
#[serde(default)]
|
||||
pub limit: Option<u32>,
|
||||
/// Cursor from a previous call ("next cursor").
|
||||
#[serde(default)]
|
||||
pub cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
/// Max outline depth to show (0 = top-level blocks only).
|
||||
#[serde(default)]
|
||||
pub max_depth: Option<u32>,
|
||||
/// Append each block's own id as a trailing `((id))` (default true; needed to edit blocks).
|
||||
#[serde(default)]
|
||||
pub ids: Option<bool>,
|
||||
/// Max blocks per call (default 400).
|
||||
#[serde(default)]
|
||||
pub limit: Option<u32>,
|
||||
/// Cursor from a previous call ("next cursor").
|
||||
#[serde(default)]
|
||||
pub cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
/// Range start (YYYY-MM-DD). With `to`: every existing journal in the range (max 31 days).
|
||||
#[serde(default)]
|
||||
pub from: Option<String>,
|
||||
/// Range end (YYYY-MM-DD, default today).
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
/// Append block ids as `((id))` (default true).
|
||||
#[serde(default)]
|
||||
pub ids: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
|
||||
pub struct ListPagesParams {
|
||||
/// Only pages of this type.
|
||||
#[serde(default, rename = "type")]
|
||||
pub page_type: Option<String>,
|
||||
/// Only pages with this tag (explicit, from their type or their hub).
|
||||
#[serde(default)]
|
||||
pub tag: Option<String>,
|
||||
/// Only direct members of this hub (title).
|
||||
#[serde(default)]
|
||||
pub hub: Option<String>,
|
||||
/// Only notes without a type (journals and hubs excluded).
|
||||
#[serde(default)]
|
||||
pub untyped: Option<bool>,
|
||||
/// Only notes without explicit tags (journals and hubs excluded).
|
||||
#[serde(default)]
|
||||
pub untagged: Option<bool>,
|
||||
/// Only pages edited on or after this date (YYYY-MM-DD).
|
||||
#[serde(default)]
|
||||
pub updated_since: Option<String>,
|
||||
/// Only pages created on or after this date (YYYY-MM-DD).
|
||||
#[serde(default)]
|
||||
pub created_since: Option<String>,
|
||||
/// Journals: "exclude" (default), "include" or "only".
|
||||
#[serde(default)]
|
||||
pub journals: Option<String>,
|
||||
/// Sort: "updated" (default, newest first), "created" (newest first) or "title".
|
||||
#[serde(default)]
|
||||
pub sort: Option<String>,
|
||||
/// Max results (default 50, max 200).
|
||||
#[serde(default)]
|
||||
pub limit: Option<u32>,
|
||||
/// Cursor from a previous call.
|
||||
#[serde(default)]
|
||||
pub cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[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<u32>,
|
||||
/// Cursor from a previous call (backlinks only).
|
||||
#[serde(default)]
|
||||
pub cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
|
||||
pub struct ListParams {
|
||||
/// Max items (default 100).
|
||||
#[serde(default)]
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
/// In the tree, also list each hub's member notes (default false).
|
||||
#[serde(default)]
|
||||
pub members: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
|
||||
pub struct RangeParams {
|
||||
/// Start date (YYYY-MM-DD, default 7 days before `to`).
|
||||
#[serde(default)]
|
||||
pub from: Option<String>,
|
||||
/// End date (YYYY-MM-DD or "today", default today).
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
/// Tags. Reuse names from list_tags when possible.
|
||||
#[serde(default)]
|
||||
pub tags: Option<Vec<String>>,
|
||||
/// Hub (title of an existing hub) to file the page under.
|
||||
#[serde(default)]
|
||||
pub hub: Option<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<Vec<String>>,
|
||||
/// Tags to add.
|
||||
#[serde(default)]
|
||||
pub add: Option<Vec<String>>,
|
||||
/// Tags to remove.
|
||||
#[serde(default)]
|
||||
pub remove: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
@@ -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::<Vec<_>>().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<char> = flat.chars().collect();
|
||||
if chars.len() <= width {
|
||||
return flat;
|
||||
}
|
||||
let folded: Vec<char> = 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<String> {
|
||||
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('…'));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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");
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
Reference in new issue
Block a user