fix(mcp): harden stdio opens, commits and user-supplied ranges

- Check per call that synapse.db exists and is on this binary's schema, so
  the stdio server never migrates or re-stamps the app's live database.
- Keep the transaction open (rolled back on drop) when COMMIT fails.
- Reject dates outside years 1000-9999 and oversized cursors (overflow).
- core: export SCHEMA_VERSION.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:22:14 +01:00
1 parent 0253cd4180
commit 4195374c23
5 files changed
+115 -4

No files matched your search

+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,
+45 -2
View File
@@ -75,7 +75,7 @@ impl GraphHost for LocalHost {
let dir = self.dir.clone();
Box::pin(async move {
tokio::task::spawn_blocking(move || {
let g = Graph::open(&dir).map_err(ToolError::from)?;
let g = open_local(&dir)?;
job(&g)
})
.await
@@ -84,6 +84,48 @@ impl GraphHost for LocalHost {
}
}
/// Opens the app's graph without surprises: it must still exist (never re-created) and be
/// on this binary's schema (`Graph::open` would migrate or re-stamp a live database).
fn open_local(dir: &std::path::Path) -> Result<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,
@@ -96,8 +138,9 @@ impl<'a> Txn<'a> {
Ok(Self { g, open: true })
}
fn commit(mut self) -> Result<(), ToolError> {
self.open = false;
// On failure `open` stays true and Drop rolls back, so no transaction leaks.
self.g.conn().execute_batch("COMMIT")?;
self.open = false;
Ok(())
}
}
+11 -2
View File
@@ -69,6 +69,8 @@ impl From<rusqlite::Error> for ToolError {
pub type ToolResult = Result<String, ToolError>;
const MAX_RANGE_DAYS: i64 = 31;
/// Cursors are offsets; capped so offset arithmetic cannot overflow.
const MAX_CURSOR: usize = 1 << 32;
const MAX_TIMELINE_DAYS: i64 = 92;
// ------------------------------------------------------------------ helpers
@@ -98,7 +100,10 @@ pub fn parse_date(g: &Graph, s: &str) -> Result<NaiveDate, ToolError> {
"yesterday" => Ok(today - Duration::days(1)),
"tomorrow" => Ok(today + Duration::days(1)),
_ => NaiveDate::parse_from_str(s, "%Y-%m-%d")
.map_err(|_| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))),
.ok()
// Sane years only: date arithmetic near chrono's limits would overflow.
.filter(|d| (1000..=9999).contains(&chrono::Datelike::year(d)))
.ok_or_else(|| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))),
}
}
@@ -131,7 +136,11 @@ fn date_range(
fn parse_cursor(c: &Option<String>) -> Result<usize, ToolError> {
match c.as_deref().map(str::trim).filter(|c| !c.is_empty()) {
None => Ok(0),
Some(c) => c.parse().map_err(|_| err(format!("bad cursor {c:?}"))),
Some(c) => c
.parse::<usize>()
.ok()
.filter(|n| *n <= MAX_CURSOR)
.ok_or_else(|| err(format!("bad cursor {c:?}"))),
}
}
+33
View File
@@ -161,3 +161,36 @@ fn refuses_a_missing_graph() {
assert!(!out.status.success());
assert!(!dir.path().join("nope").exists(), "must not create a graph");
}
#[test]
fn refuses_a_graph_on_another_schema() {
let dir = tempfile::tempdir().unwrap();
{
let g = Graph::open(dir.path()).unwrap();
g.conn()
.execute("UPDATE meta SET value='1' WHERE key='schema'", [])
.unwrap();
}
let mut s = Server::start(dir.path(), &[]);
s.init();
let r = s.call(
2,
"tools/call",
json!({"name": "list_pages", "arguments": {}}),
);
let text = r["result"]["content"][0]["text"].as_str().unwrap();
assert!(text.contains("schema is v1"), "{r}");
drop(s);
let g = Graph::open(dir.path()).unwrap();
let v: String = g
.conn()
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
r.get(0)
})
.unwrap();
assert_eq!(
v,
synapse_core::SCHEMA_VERSION.to_string(),
"re-opened by core only here"
);
}
+25
View File
@@ -620,3 +620,28 @@ fn resources_render_pages() {
let out = read(&g, |g| tools::page_resource(g, "Dune"));
assert!(out.contains("- Arrakis is a desert planet\n"), "{out}");
}
#[test]
fn extreme_dates_and_cursors_are_rejected() {
let (_d, g) = fixture();
let e = read_err(&g, |g| {
tools::timeline(
g,
&RangeParams {
from: None,
to: Some("-262143-01-03".into()),
},
)
});
assert!(e.contains("bad date"), "{e}");
let e = read_err(&g, |g| {
tools::list_pages(
g,
&ListPagesParams {
cursor: Some(usize::MAX.to_string()),
..Default::default()
},
)
});
assert!(e.contains("bad cursor"), "{e}");
}