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:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:09:41 +01:00
1 parent c8f7cdaf92
commit c0f0716d3b
9 files changed
+3308

No files matched your search

+552
View File
@@ -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()
}
+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