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

+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:?}"))),
}
}