Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat: add /api/update and /api/lineage REST endpoints

FABIOTESSfb89191e2ca3
diff --git a/Cargo.lock b/Cargo.lock
index b78b5913..20b5a582 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2373,6 +2373,7 @@ dependencies = [
"tokio",
"tokio-util",
"toml",
+ "tower-http",
"tracing",
"tracing-subscriber",
"tract-onnx",
diff --git a/Cargo.toml b/Cargo.toml
index a86b5b95..aa7b35d0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,6 +13,7 @@ path = "src/main.rs"
[dependencies]
rmcp = { version = "1", features = ["server", "transport-io", "transport-streamable-http-server"] }
axum = "0.8"
+tower-http = { version = "0.6", features = ["cors"] }
tokio-util = "0.7"
tokio = { version = "1", features = ["full"] }
oxigraph = "0.4"
diff --git a/src/inputs.rs b/src/inputs.rs
index 2d6400c8..f0045c1f 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -23,8 +23,10 @@ pub struct OntoConvertInput {
#[derive(Deserialize, JsonSchema)]
pub struct OntoLoadInput {
- /// Path to RDF file to load into the in-memory store
- pub path: String,
+ /// Path to RDF file, OR inline Turtle/RDF content
+ pub path: Option<String>,
+ /// Inline Turtle content to load (alternative to path)
+ pub turtle: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/main.rs b/src/main.rs
index 0ac2509f..53537940 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -415,6 +415,12 @@ async fn main() -> anyhow::Result<()> {
std::fs::create_dir_all(&data_dir)?;
+ // Shared graph store — all MCP sessions (agent + frontend) see the same triples
+ let shared_graph = Arc::new(GraphStore::new());
+
+ // Shared StateDb for lineage REST endpoint
+ let shared_db = StateDb::open(&db_path_owned)?;
+
let ct = CancellationToken::new();
let http_config = StreamableHttpServerConfig {
stateful_mode: true,
@@ -422,18 +428,97 @@ async fn main() -> anyhow::Result<()> {
..Default::default()
};
+ let shared_graph_for_service = shared_graph.clone();
let service: StreamableHttpService<_, LocalSessionManager> =
StreamableHttpService::new(
move || {
let db = StateDb::open(&db_path_owned)
.map_err(std::io::Error::other)?;
- Ok(OpenOntologiesServer::new(db))
+ Ok(OpenOntologiesServer::new_with_graph(db, shared_graph_for_service.clone()))
},
Default::default(),
http_config,
);
- let router = axum::Router::new().nest_service("/mcp", service);
+ // Simple REST API — no MCP sessions, direct access to shared graph
+ let sg_stats = shared_graph.clone();
+ let sg_query = shared_graph.clone();
+ let sg_update = shared_graph.clone();
+ let sg_load = shared_graph.clone();
+ let api = axum::Router::new()
+ .route("/stats", axum::routing::get(move || {
+ let g = sg_stats.clone();
+ async move {
+ axum::Json(serde_json::from_str::<serde_json::Value>(
+ &g.get_stats().unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
+ ).unwrap_or_default())
+ }
+ }))
+ .route("/query", axum::routing::post(move |body: axum::Json<serde_json::Value>| {
+ let g = sg_query.clone();
+ async move {
+ let query = body.0["query"].as_str().unwrap_or("").to_string();
+ axum::Json(serde_json::from_str::<serde_json::Value>(
+ &g.sparql_select(&query).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
+ ).unwrap_or_default())
+ }
+ }))
+ .route("/update", axum::routing::post(move |body: axum::Json<serde_json::Value>| {
+ let g = sg_update.clone();
+ async move {
+ let query = body.0["query"].as_str().unwrap_or("").to_string();
+ axum::Json(serde_json::from_str::<serde_json::Value>(
+ &match g.sparql_update(&query) {
+ Ok(n) => format!(r#"{{"ok":true,"affected":{}}}"#, n),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ ).unwrap_or_default())
+ }
+ }))
+ .route("/load", axum::routing::post(move |body: axum::Json<serde_json::Value>| {
+ let g = sg_load.clone();
+ async move {
+ let path = body.0["path"].as_str().unwrap_or("").to_string();
+ let path = open_ontologies::config::expand_tilde(&path);
+ axum::Json(serde_json::from_str::<serde_json::Value>(
+ &match g.load_file(&path) {
+ Ok(n) => format!(r#"{{"ok":true,"triples_loaded":{}}}"#, n),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ ).unwrap_or_default())
+ }
+ }))
+ .route("/lineage", axum::routing::get(move || {
+ let db = shared_db.clone();
+ async move {
+ let conn = db.conn();
+ let mut stmt = conn.prepare(
+ "SELECT session_id, seq, timestamp, event_type, operation, details \
+ FROM lineage_events ORDER BY CAST(timestamp AS INTEGER) ASC, seq ASC LIMIT 500"
+ ).unwrap();
+ let rows: Vec<serde_json::Value> = stmt.query_map([], |row| {
+ let session_id: String = row.get(0)?;
+ let seq: i64 = row.get(1)?;
+ let timestamp: String = row.get(2)?;
+ let event_type: String = row.get(3)?;
+ let operation: String = row.get(4)?;
+ let details: String = row.get::<_, Option<String>>(5)?.unwrap_or_default();
+ Ok(serde_json::json!({
+ "session": session_id,
+ "seq": seq,
+ "ts": timestamp,
+ "type": event_type,
+ "op": operation,
+ "details": details
+ }))
+ }).unwrap().filter_map(|r| r.ok()).collect();
+ axum::Json(serde_json::json!({ "events": rows }))
+ }
+ }));
+
+ let router = axum::Router::new()
+ .nest("/api", api)
+ .nest_service("/mcp", service);
let router = if let Some(ref token) = token {
let expected = format!("Bearer {}", token);
router.layer(axum::middleware::from_fn(move |req: axum::extract::Request, next: axum::middleware::Next| {
@@ -453,6 +538,7 @@ async fn main() -> anyhow::Result<()> {
} else {
router
};
+ let router = router.layer(tower_http::cors::CorsLayer::permissive());
let addr = format!("{host}:{port}");
let listener = tokio::net::TcpListener::bind(&addr).await?;
eprintln!("Open Ontologies MCP server listening on http://{addr}/mcp");
diff --git a/src/server.rs b/src/server.rs
index 13843281..86d3aa9b 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -11,6 +11,7 @@ use rmcp::{
},
service::RequestContext,
};
+use crate::config::expand_tilde;
use crate::graph::GraphStore;
use crate::inputs::*;
use crate::state::StateDb;
@@ -34,6 +35,12 @@ pub struct OpenOntologiesServer {
impl OpenOntologiesServer {
/// Create a new server with all tools wired to domain services.
pub fn new(db: StateDb) -> Self {
+ Self::new_with_graph(db, Arc::new(GraphStore::new()))
+ }
+
+ /// Create a new server sharing an existing graph store (for HTTP mode where
+ /// all sessions must see the same in-memory triples).
+ pub fn new_with_graph(db: StateDb, graph: Arc<GraphStore>) -> Self {
let lineage = crate::lineage::LineageLog::new(db.clone());
let session_id = lineage.new_session();
@@ -63,7 +70,7 @@ impl OpenOntologiesServer {
tool_router: Self::tool_router(),
prompt_router: Self::prompt_router(),
db,
- graph: Arc::new(GraphStore::new()),
+ graph,
session_id,
#[cfg(feature = "embeddings")]
vecstore,
@@ -141,11 +148,21 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_load", description = "Load an RDF file into the in-memory ontology store for querying")]
+ #[tool(name = "onto_load", description = "Load an RDF file or inline Turtle content into the in-memory ontology store for querying")]
async fn onto_load(&self, Parameters(input): Parameters<OntoLoadInput>) -> String {
- match self.graph.load_file(&input.path) {
- Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"path":"{}"}}"#, count, input.path),
- Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ if let Some(turtle) = input.turtle {
+ match self.graph.load_turtle(&turtle, None) {
+ Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"source":"inline"}}"#, count),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ } else if let Some(path) = input.path {
+ let path = expand_tilde(&path);
+ match self.graph.load_file(&path) {
+ Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"path":"{}"}}"#, count, path),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ } else {
+ r#"{"error":"Either 'path' or 'turtle' must be provided"}"#.to_string()
}
}
@@ -157,8 +174,9 @@ impl OpenOntologiesServer {
#[tool(name = "onto_save", description = "Save the current ontology store to a file")]
async fn onto_save(&self, Parameters(input): Parameters<OntoSaveInput>) -> String {
let format = input.format.as_deref().unwrap_or("turtle");
- match self.graph.save_file(&input.path, format) {
- Ok(_) => format!(r#"{{"ok":true,"path":"{}","format":"{}"}}"#, input.path, format),
+ let path = expand_tilde(&input.path);
+ match self.graph.save_file(&path, format) {
+ Ok(_) => format!(r#"{{"ok":true,"path":"{}","format":"{}"}}"#, path, format),
Err(e) => format!(r#"{{"error":"{}"}}"#, e),
}
}