Merge pull request #6 from Dasemu/feat/mcp-server

feat: MCP server for AI assistants (stdio + Streamable HTTP)
This commit is contained in:
dasemu authored and GitHub committed 2026-10-28 16:34:20 +01:00
commit b08bbd1883
25 files changed
+3956 -9

No files matched your search

+8
View File
@@ -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
+3
View File
@@ -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 <copy of a 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
Generated
+159
View File
@@ -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"
@@ -3361,6 +3508,7 @@ dependencies = [
"serde",
"serde_json",
"synapse-core",
"synapse-mcp",
"synapse-sync",
"tempfile",
"tokio",
@@ -3688,6 +3836,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"
+2 -1
View File
@@ -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).
+1
View File
@@ -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,
+13 -3
View File
@@ -19,6 +19,9 @@ pub struct CacheKey {
seq: i64,
synapses: i64,
synapse_last: i64,
/// Sum of raw weights (micro-units): a re-fire within the same millisecond keeps count
/// and `last_fired` but changes the weight.
synapse_weight: i64,
/// Synapse weights decay with time: rebuild at least hourly.
hour: i64,
}
@@ -47,15 +50,22 @@ impl SynapseGraph {
}
fn cache_key(g: &Graph) -> Result<CacheKey> {
let (synapses, synapse_last) = g.conn().query_row(
"SELECT count(*), coalesce(max(last_fired), 0) FROM synapses",
let (synapses, synapse_last, weight) = g.conn().query_row(
"SELECT count(*), coalesce(max(last_fired), 0), total(weight) FROM synapses",
[],
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|r| {
Ok((
r.get::<_, i64>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, f64>(2)?,
))
},
)?;
Ok(CacheKey {
seq: g.last_seq()?,
synapses,
synapse_last,
synapse_weight: (weight * 1e6).round() as i64,
hour: g.now_ms() / 3_600_000,
})
}
+1 -1
View File
@@ -7,7 +7,7 @@
mod config;
mod names;
mod outline;
pub mod outline;
mod rewrite;
mod track;
+31
View File
@@ -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"
+597
View File
@@ -0,0 +1,597 @@
//! 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 use rmcp;
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 = open_local(&dir)?;
job(&g)
})
.await
.map_err(|e| ToolError::new(format!("internal error: {e}")))?
})
}
}
/// 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<Graph, ToolError> {
let db = dir.join("synapse.db");
if !db.is_file() {
return Err(ToolError::new(format!("graph {} is gone", dir.display())));
}
let schema: Option<String> = {
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<Graph, ToolError>) -> Result<Graph, ToolError> {
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,
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> {
// On failure `open` stays true and Drop rolls back, so no transaction leaks.
self.g.conn().execute_batch("COMMIT")?;
self.open = false;
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()
}
+80
View File
@@ -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}"));
}
}
+236
View File
@@ -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>,
}
+133
View File
@@ -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
+196
View File
@@ -0,0 +1,196 @@
//! 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");
}
#[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"
);
}
+647
View File
@@ -0,0 +1,647 @@
//! 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}");
}
#[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}");
}
+2
View File
@@ -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
+50 -1
View File
@@ -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<McpConfig>,
}
/// 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<String>,
/// 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<String>,
}
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<Self, String> {
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<String> {
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,23 @@ 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());
}
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
.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"
+12 -3
View File
@@ -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<admin::Updater>,
pub(crate) shutdown: Arc<Notify>,
pub(crate) max_clock_skew: std::time::Duration,
/// MCP endpoint state; `None` when `SYNAPSE_MCP_TOKEN` is unset.
pub(crate) mcp: Option<Arc<mcp::McpState>>,
pub(crate) mcp_config: Option<config::McpConfig>,
}
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)
}
+106
View File
@@ -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<GraphHandle>);
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<AppState>,
Path(id): Path<String>,
mut req: Request,
next: Next,
) -> Result<Response, ApiError> {
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<AppState> {
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))
}
+1
View File
@@ -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 }
+205
View File
@@ -0,0 +1,205 @@
//! 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<String> {
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();
}
#[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());
}
+1
View File
@@ -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.
+2
View File
@@ -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
+125
View File
@@ -0,0 +1,125 @@
# 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/<graph-id>/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 <url> --header "Authorization: Bearer <token>"`.
## 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. 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).
- **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
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
- 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.
- 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.
+3
View File
@@ -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` |