feat(server): serve MCP over Streamable HTTP at /v1/graphs/{id}/mcp

Enabled by SYNAPSE_MCP_TOKEN (own bearer tokens, constant-time check),
write tools with SYNAPSE_MCP_ALLOW_WRITE=1, Host allowlist via
SYNAPSE_MCP_ALLOWED_HOSTS. Stateless JSON responses; tools run on the shared
graph handle and wake SSE subscribers after writes. Never creates graphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:13:44 +01:00
1 parent c0f0716d3b
commit 8459838d01
10 files changed
+367 -4

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
Generated
+1
View File
@@ -3508,6 +3508,7 @@ dependencies = [
"serde",
"serde_json",
"synapse-core",
"synapse-mcp",
"synapse-sync",
"tempfile",
"tokio",
+2
View File
@@ -12,6 +12,8 @@
//! 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;
+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
+45 -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,18 @@ 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());
}
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 }
+187
View File
@@ -0,0 +1,187 @@
//! 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();
}
+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` |