mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
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:
1 parent
c0f0716d3b
commit
8459838d01
10 files changed
+367
-4
No files matched your search
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
Reference in new issue
Block a user