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: ontology_dirs config + onto_repo_list/onto_repo_load tools (PR #11)

FABIOTESS547724ab30a9
diff --git a/README.md b/README.md
index 980e25bb..cf89ac07 100644
--- a/README.md
+++ b/README.md
@@ -638,6 +638,7 @@ The same tool, applied to any ontology, produces the same kind of improvement. T
| Category | Tools | Purpose |
| --- | --- | --- |
| **Core** | `validate` `load` `save` `clear` `stats` `query` `diff` `lint` `convert` `status` | RDF/OWL validation, querying, and management |
+| **Repository** | `repo_list` `repo_load` | Browse and load ontologies from configured `[general] ontology_dirs` directories |
| **Marketplace** | `marketplace` | Browse and install 32 standard W3C/ISO/industry ontologies |
| **Remote** | `pull` `push` `import` | Fetch/push ontologies, resolve owl:imports |
| **Schema** | `import-schema` | PostgreSQL → OWL conversion |
diff --git a/docs/cache-and-registry.md b/docs/cache-and-registry.md
index 8d2e5230..2054a643 100644
--- a/docs/cache-and-registry.md
+++ b/docs/cache-and-registry.md
@@ -104,6 +104,39 @@ via `tools/call`.
| `onto_cache_status` | Active slot, all cache rows, and effective config. |
| `onto_cache_list` | Lighter alternative to `onto_cache_status` — returns just the array of cached ontologies with metadata and `is_active`/`in_memory` flags. |
| `onto_cache_remove` | Remove a cached ontology by name. If it is the active slot, the in-memory store is unloaded first. By default the on-disk N-Triples file is also deleted; pass `delete_file=false` to keep it. |
+| `onto_repo_list` | List RDF/OWL files in the configured `[general] ontology_dirs` directories. Returns `path`, `name`, `size`, `mtime`, `is_cached`, `is_active` for each entry. Optional `dir` (must be inside a configured repo), `recursive`, `glob`, `limit`, `offset`. |
+| `onto_repo_load` | Load an ontology from a configured repo by bare name (file stem), relative path, or absolute path inside a repo. Reuses the same compile-cache / TTL-eviction path as `onto_load`. |
+
+## Ontology repository directories
+
+In addition to single-file `onto_load`, the server can be pointed at one or
+more host directories that act as on-disk repositories of ontologies. This
+is the recommended pattern for containerized deployments: mount a host
+folder of `.ttl` files and the server enumerates them on demand.
+
+```toml
+[general]
+data_dir = "~/.open-ontologies"
+# Either name works; `data_dirs` is accepted as an alias.
+ontology_dirs = ["./ttl_data", "/srv/ontologies"]
+```
+
+The `OPEN_ONTOLOGIES_ONTOLOGY_DIRS` environment variable overrides the
+config (`:` separated on Unix, `;` on Windows; either accepted on both):
+
+```sh
+OPEN_ONTOLOGIES_ONTOLOGY_DIRS=/srv/ontologies:/data/extra open-ontologies serve
+```
+
+Use the new MCP tools to interact with the repo:
+
+- `onto_repo_list` returns the full catalogue with `is_cached` / `is_active`
+ flags so a client can show which entries are already compiled.
+- `onto_repo_load` resolves a bare stem (e.g. `pizza`), a relative path
+ (e.g. `domain/pizza.ttl`), or an absolute path that must lie inside one
+ of the configured repos. Paths outside the configured directories are
+ rejected (path-traversal guard).
+
### Managing multiple cached ontologies
diff --git a/src/config.rs b/src/config.rs
index 54f8e70f..f9602d1d 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -27,16 +27,62 @@ impl Config {
#[serde(default)]
pub struct GeneralConfig {
pub data_dir: String,
+ /// Directories that act as on-disk ontology repositories. The
+ /// `onto_repo_list` and `onto_repo_load` MCP tools enumerate and load
+ /// RDF files (.ttl, .nt, .rdf, .owl, .nq, .trig, .jsonld) from these
+ /// directories. Useful for containerized deployments where a host
+ /// directory of TTL files is mounted into the server.
+ ///
+ /// Accepts either a TOML array under the canonical name `ontology_dirs`
+ /// or, for compatibility with the original design proposal, the alias
+ /// `data_dirs`. Each entry has `~` expanded to the user's home.
+ #[serde(alias = "data_dirs")]
+ pub ontology_dirs: Vec<String>,
}
impl Default for GeneralConfig {
fn default() -> Self {
Self {
data_dir: "~/.open-ontologies".into(),
+ ontology_dirs: Vec::new(),
}
}
}
+/// Resolve the configured ontology repository directories.
+///
+/// Behavior:
+/// - If the env var `OPEN_ONTOLOGIES_ONTOLOGY_DIRS` is set and non-empty,
+/// its value (split on `:` on Unix, `;` on Windows, accepting either on
+/// both for convenience) overrides the config entries.
+/// - Each entry has `~` expanded.
+/// - Empty strings are dropped.
+/// - Duplicates (after canonicalization fallback to the expanded string)
+/// are removed while preserving order.
+pub fn resolve_ontology_dirs(cfg: &[String]) -> Vec<std::path::PathBuf> {
+ let from_env = std::env::var("OPEN_ONTOLOGIES_ONTOLOGY_DIRS").ok();
+ let raw: Vec<String> = match from_env {
+ Some(v) if !v.trim().is_empty() => v
+ .split(|c| c == ':' || c == ';')
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect(),
+ _ => cfg.iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
+ };
+ let mut seen = std::collections::HashSet::new();
+ let mut out = Vec::with_capacity(raw.len());
+ for entry in raw {
+ let expanded = expand_tilde(&entry);
+ let key = std::fs::canonicalize(&expanded)
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_else(|_| expanded.clone());
+ if seen.insert(key) {
+ out.push(std::path::PathBuf::from(expanded));
+ }
+ }
+ out
+}
+
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct EmbeddingsConfig {
diff --git a/src/inputs.rs b/src/inputs.rs
index 5f1ea1a5..2b455ea2 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -57,6 +57,42 @@ pub struct OntoRecompileInput {
pub name: Option<String>,
}
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoRepoListInput {
+ /// Optional subdirectory to scan instead of every configured ontology
+ /// repo. Must resolve under one of the configured `ontology_dirs`
+ /// entries; arbitrary host paths are rejected (path-traversal guard).
+ pub dir: Option<String>,
+ /// Walk subdirectories recursively. Defaults to false (top-level only).
+ pub recursive: Option<bool>,
+ /// Optional filename glob filter (e.g. `*.ttl`, `foo*`). Matches the
+ /// filename only, not the full path.
+ pub glob: Option<String>,
+ /// Maximum number of entries to return. Default 1000.
+ pub limit: Option<usize>,
+ /// Skip the first `offset` entries (for pagination). Default 0.
+ pub offset: Option<usize>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoRepoLoadInput {
+ /// Identifier of the ontology to load. Accepts:
+ /// - a bare name (e.g. `pizza`) matching a file stem under any
+ /// configured `ontology_dirs`,
+ /// - a relative path (e.g. `subdir/pizza.ttl`) resolved against the
+ /// configured directories,
+ /// - an absolute path inside one of the configured directories.
+ /// Paths outside the configured `ontology_dirs` are rejected.
+ pub name: String,
+ /// Optional registry name override (defaults to the file stem).
+ pub registry_name: Option<String>,
+ /// When true, every subsequent read tool checks the source file's mtime
+ /// and recompiles if it changed.
+ pub auto_refresh: Option<bool>,
+ /// When true, ignore the on-disk compile cache and re-parse from source.
+ pub force_recompile: Option<bool>,
+}
+
#[derive(Deserialize, JsonSchema)]
pub struct OntoCacheStatusInput {}
diff --git a/src/lib.rs b/src/lib.rs
index f3f7374c..b71af376 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,6 +19,7 @@ pub mod marketplace;
pub mod ontology;
pub mod reason;
pub mod registry;
+pub mod repo;
pub mod server;
pub mod shacl;
pub mod state;
diff --git a/src/main.rs b/src/main.rs
index 0b736c57..8da508c5 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,6 +10,14 @@ use open_ontologies::state::StateDb;
const DEFAULT_CONFIG: &str = r#"[general]
data_dir = "~/.open-ontologies"
+# Optional on-disk ontology repository directories. When set, the
+# `onto_repo_list` and `onto_repo_load` MCP tools enumerate and load
+# RDF/OWL files (.ttl, .nt, .rdf, .owl, .nq, .trig, .jsonld) from these
+# directories. Container-friendly: mount a host folder of TTL files.
+# Override at runtime with the `OPEN_ONTOLOGIES_ONTOLOGY_DIRS` env var
+# (':' separated on Unix, ';' on Windows; either accepted on both).
+# ontology_dirs = ["./ttl_data"]
+
# [cache]
# Compile-cache: parsed ontologies are written to N-Triples files for fast reload.
# enabled = true
@@ -583,13 +591,20 @@ async fn main() -> anyhow::Result<()> {
let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
- let server = OpenOntologiesServer::new_with_registry_options(
+ let ontology_dirs = open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
+ for d in &ontology_dirs {
+ if !d.exists() {
+ eprintln!("warning: ontology_dirs entry does not exist: {}", d.display());
+ }
+ }
+ let server = OpenOntologiesServer::new_with_repo_options(
db,
graph,
governance_webhook,
cfg.embeddings,
cache_config,
tool_filter,
+ ontology_dirs,
);
let _evictor = open_ontologies::registry::spawn_evictor(server.registry());
let service = server.serve(rmcp::transport::stdio()).await?;
@@ -648,6 +663,12 @@ async fn main() -> anyhow::Result<()> {
let embed_config = cfg.embeddings.clone();
let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
+ let ontology_dirs = open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);
+ for d in &ontology_dirs {
+ if !d.exists() {
+ eprintln!("warning: ontology_dirs entry does not exist: {}", d.display());
+ }
+ }
// Spawn a single evictor backed by a registry over the shared graph.
// Each per-session server constructs its own registry (active slot
// is per-session anyway), but the shared one drives memory cleanup.
@@ -662,18 +683,20 @@ async fn main() -> anyhow::Result<()> {
}
let cache_for_service = cache_config.clone();
let filter_for_service = tool_filter.clone();
+ let dirs_for_service = ontology_dirs.clone();
let service: StreamableHttpService<_, LocalSessionManager> =
StreamableHttpService::new(
move || {
let db = StateDb::open(&db_path_owned)
.map_err(std::io::Error::other)?;
- Ok(OpenOntologiesServer::new_with_registry_options(
+ Ok(OpenOntologiesServer::new_with_repo_options(
db,
shared_graph_for_service.clone(),
gw_for_service.clone(),
embed_config.clone(),
cache_for_service.clone(),
filter_for_service.clone(),
+ dirs_for_service.clone(),
))
},
Default::default(),
diff --git a/src/repo.rs b/src/repo.rs
new file mode 100644
index 00000000..8196570b
--- /dev/null
+++ b/src/repo.rs
@@ -0,0 +1,283 @@
+//! On-disk ontology repository support.
+//!
+//! A "repo" is one or more host directories (configured via
+//! `[general] ontology_dirs` or the `OPEN_ONTOLOGIES_ONTOLOGY_DIRS` env var)
+//! that contain RDF/OWL files the server can list and load on demand.
+//!
+//! This module is dependency-free of the MCP layer — it only deals with
+//! filesystem walking, extension filtering, glob matching, and safe path
+//! resolution. The MCP tools (`onto_repo_list`, `onto_repo_load`) live in
+//! `src/server.rs` and use the helpers below.
+use std::path::{Path, PathBuf};
+use std::time::UNIX_EPOCH;
+
+use anyhow::{anyhow, Result};
+
+/// File extensions the RDF parser (`GraphStore::detect_format`) accepts.
+/// Lowercased, without the leading dot. Keep in sync with `graph.rs`.
+pub const RDF_EXTENSIONS: &[&str] = &[
+ "ttl", "turtle", "nt", "ntriples", "rdf", "xml", "owl", "nq", "trig", "jsonld",
+];
+
+/// True if `path`'s extension is one of `RDF_EXTENSIONS` (case-insensitive).
+pub fn has_rdf_extension(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| {
+ let lower = e.to_ascii_lowercase();
+ RDF_EXTENSIONS.iter().any(|x| *x == lower.as_str())
+ })
+ .unwrap_or(false)
+}
+
+/// One discovered ontology file within a configured repo directory.
+#[derive(Debug, Clone)]
+pub struct RepoEntry {
+ /// Absolute path on disk.
+ pub path: PathBuf,
+ /// Path relative to the repo dir it was found under.
+ pub relative: PathBuf,
+ /// Repo dir this entry belongs to.
+ pub repo_dir: PathBuf,
+ /// Default ontology name (file stem).
+ pub name: String,
+ pub size: u64,
+ pub mtime_secs: i64,
+}
+
+/// Minimal fnmatch-style glob: supports `*` and `?` against a single filename
+/// (no path separators). This is intentionally tiny so we don't pull in a
+/// glob crate just for filtering tool output.
+pub fn glob_match(pattern: &str, name: &str) -> bool {
+ fn helper(p: &[u8], n: &[u8]) -> bool {
+ match (p.first(), n.first()) {
+ (None, None) => true,
+ (Some(b'*'), _) => {
+ // Try consuming zero or more characters from `n`.
+ if helper(&p[1..], n) {
+ return true;
+ }
+ if !n.is_empty() && helper(p, &n[1..]) {
+ return true;
+ }
+ false
+ }
+ (Some(b'?'), Some(_)) => helper(&p[1..], &n[1..]),
+ (Some(pc), Some(nc)) if pc.eq_ignore_ascii_case(nc) => helper(&p[1..], &n[1..]),
+ _ => false,
+ }
+ }
+ helper(pattern.as_bytes(), name.as_bytes())
+}
+
+/// Normalize `dir` to an absolute path that lies inside one of the configured
+/// repo directories. Returns the resolved path *and* the matching repo dir.
+///
+/// This is the path-traversal guard: callers cannot pass arbitrary host
+/// paths via the `dir` argument of `onto_repo_list`.
+pub fn resolve_within_repos(dir: &str, repos: &[PathBuf]) -> Result<(PathBuf, PathBuf)> {
+ if repos.is_empty() {
+ return Err(anyhow!(
+ "no ontology_dirs configured; set [general] ontology_dirs in config.toml or OPEN_ONTOLOGIES_ONTOLOGY_DIRS"
+ ));
+ }
+ let candidate = if Path::new(dir).is_absolute() {
+ PathBuf::from(crate::config::expand_tilde(dir))
+ } else {
+ // Relative paths are resolved against each repo dir in order; the
+ // first existing match wins.
+ repos
+ .iter()
+ .map(|r| r.join(dir))
+ .find(|p| p.exists())
+ .unwrap_or_else(|| repos[0].join(dir))
+ };
+ let canon = std::fs::canonicalize(&candidate).unwrap_or_else(|_| candidate.clone());
+
+ for repo in repos {
+ let repo_canon = std::fs::canonicalize(repo).unwrap_or_else(|_| repo.clone());
+ if canon.starts_with(&repo_canon) {
+ return Ok((canon, repo_canon));
+ }
+ }
+ Err(anyhow!(
+ "directory '{}' is not under any configured ontology_dirs",
+ dir
+ ))
+}
+
+/// Walk a single directory (optionally recursively) collecting RDF files.
+fn walk(repo_dir: &Path, start: &Path, recursive: bool, out: &mut Vec<RepoEntry>) {
+ let read = match std::fs::read_dir(start) {
+ Ok(r) => r,
+ Err(_) => return,
+ };
+ for entry in read.flatten() {
+ let path = entry.path();
+ let ft = match entry.file_type() {
+ Ok(t) => t,
+ Err(_) => continue,
+ };
+ if ft.is_dir() {
+ if recursive {
+ walk(repo_dir, &path, true, out);
+ }
+ continue;
+ }
+ if !ft.is_file() {
+ continue;
+ }
+ if !has_rdf_extension(&path) {
+ continue;
+ }
+ let meta = match entry.metadata() {
+ Ok(m) => m,
+ Err(_) => continue,
+ };
+ let mtime_secs = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_secs() as i64)
+ .unwrap_or(0);
+ let relative = path
+ .strip_prefix(repo_dir)
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|_| path.clone());
+ let name = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("default")
+ .to_string();
+ out.push(RepoEntry {
+ path: path.clone(),
+ relative,
+ repo_dir: repo_dir.to_path_buf(),
+ name,
+ size: meta.len(),
+ mtime_secs,
+ });
+ }
+}
+
+/// List RDF files under one repo directory.
+pub fn list_one(repo_dir: &Path, start: &Path, recursive: bool) -> Vec<RepoEntry> {
+ let mut out = Vec::new();
+ walk(repo_dir, start, recursive, &mut out);
+ // Stable order: by relative path.
+ out.sort_by(|a, b| a.relative.cmp(&b.relative));
+ out
+}
+
+/// List RDF files across all configured repo directories.
+pub fn list_all(repos: &[PathBuf], recursive: bool) -> Vec<RepoEntry> {
+ let mut out = Vec::new();
+ for repo in repos {
+ let canon = std::fs::canonicalize(repo).unwrap_or_else(|_| repo.clone());
+ walk(&canon, &canon, recursive, &mut out);
+ }
+ out.sort_by(|a, b| a.repo_dir.cmp(&b.repo_dir).then(a.relative.cmp(&b.relative)));
+ out
+}
+
+/// Resolve an `onto_repo_load` `name` argument to an absolute path that
+/// lies inside one of the configured repo directories.
+///
+/// Resolution order:
+/// 1. If `name` is an absolute path, it must already lie under a repo dir.
+/// 2. If `name` contains a path separator, treat as a relative path under
+/// each repo dir; first existing match wins.
+/// 3. Otherwise treat as a bare stem and recursively search every repo dir
+/// for a file whose stem matches and whose extension is in
+/// `RDF_EXTENSIONS`. If multiple files match, return an error listing
+/// all candidates.
+pub fn resolve_load_target(name: &str, repos: &[PathBuf]) -> Result<PathBuf> {
+ if repos.is_empty() {
+ return Err(anyhow!(
+ "no ontology_dirs configured; set [general] ontology_dirs in config.toml or OPEN_ONTOLOGIES_ONTOLOGY_DIRS"
+ ));
+ }
+ let trimmed = name.trim();
+ if trimmed.is_empty() {
+ return Err(anyhow!("name must not be empty"));
+ }
+
+ // Case 1 & 2: looks like a path.
+ let looks_like_path = trimmed.contains('/')
+ || trimmed.contains('\\')
+ || Path::new(trimmed).is_absolute()
+ || has_rdf_extension(Path::new(trimmed));
+
+ if looks_like_path {
+ let expanded = crate::config::expand_tilde(trimmed);
+ let candidate_paths: Vec<PathBuf> = if Path::new(&expanded).is_absolute() {
+ vec![PathBuf::from(&expanded)]
+ } else {
+ repos.iter().map(|r| r.join(&expanded)).collect()
+ };
+ for cand in &candidate_paths {
+ if !cand.exists() || !cand.is_file() {
+ continue;
+ }
+ let canon = std::fs::canonicalize(cand).unwrap_or_else(|_| cand.clone());
+ for repo in repos {
+ let repo_canon = std::fs::canonicalize(repo).unwrap_or_else(|_| repo.clone());
+ if canon.starts_with(&repo_canon) {
+ return Ok(canon);
+ }
+ }
+ return Err(anyhow!(
+ "path '{}' is outside the configured ontology_dirs",
+ cand.display()
+ ));
+ }
+ return Err(anyhow!("no file matching '{}' found in ontology_dirs", trimmed));
+ }
+
+ // Case 3: bare stem — recursive search across all repos.
+ let entries = list_all(repos, true);
+ let mut matches: Vec<&RepoEntry> = entries.iter().filter(|e| e.name == trimmed).collect();
+ match matches.len() {
+ 0 => Err(anyhow!(
+ "no ontology with name '{}' found in configured ontology_dirs",
+ trimmed
+ )),
+ 1 => Ok(matches.remove(0).path.clone()),
+ _ => {
+ let paths: Vec<String> = matches
+ .iter()
+ .map(|e| e.path.display().to_string())
+ .collect();
+ Err(anyhow!(
+ "ambiguous name '{}' matches {} files: {}",
+ trimmed,
+ paths.len(),
+ paths.join(", ")
+ ))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rdf_extension_recognized() {
+ assert!(has_rdf_extension(Path::new("a.ttl")));
+ assert!(has_rdf_extension(Path::new("a.TTL")));
+ assert!(has_rdf_extension(Path::new("a.owl")));
+ assert!(has_rdf_extension(Path::new("a.jsonld")));
+ assert!(!has_rdf_extension(Path::new("a.txt")));
+ assert!(!has_rdf_extension(Path::new("noext")));
+ }
+
+ #[test]
+ fn glob_basic() {
+ assert!(glob_match("*.ttl", "foo.ttl"));
+ assert!(glob_match("*", "anything"));
+ assert!(glob_match("foo?.ttl", "foo1.ttl"));
+ assert!(!glob_match("*.ttl", "foo.nt"));
+ assert!(glob_match("FOO*", "foo_bar"));
+ }
+}
diff --git a/src/server.rs b/src/server.rs
index b0ad28cf..5df07226 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -29,6 +29,10 @@ pub struct OpenOntologiesServer {
governance_webhook: Option<String>,
/// Registry tracking the active ontology + compile cache + TTL eviction.
registry: Arc<crate::registry::OntologyRegistry>,
+ /// Configured ontology repository directories, expanded and deduplicated.
+ /// Empty when none are configured. Used by `onto_repo_list` /
+ /// `onto_repo_load`.
+ ontology_dirs: Arc<Vec<std::path::PathBuf>>,
#[cfg(feature = "embeddings")]
vecstore: Arc<std::sync::Mutex<crate::vecstore::VecStore>>,
#[cfg(feature = "embeddings")]
@@ -77,6 +81,31 @@ impl OpenOntologiesServer {
_embed_config: crate::config::EmbeddingsConfig,
cache_config: crate::config::CacheConfig,
tool_filter: crate::toolfilter::ToolFilter,
+ ) -> Self {
+ Self::new_with_repo_options(
+ db,
+ graph,
+ governance_webhook,
+ _embed_config,
+ cache_config,
+ tool_filter,
+ Vec::new(),
+ )
+ }
+
+ /// Full constructor with on-disk ontology repo directories.
+ ///
+ /// `ontology_dirs` lists host directories that the `onto_repo_list` and
+ /// `onto_repo_load` tools enumerate. They are stored verbatim (already
+ /// resolved by the caller through `crate::config::resolve_ontology_dirs`).
+ pub fn new_with_repo_options(
+ db: StateDb,
+ graph: Arc<GraphStore>,
+ governance_webhook: Option<String>,
+ _embed_config: crate::config::EmbeddingsConfig,
+ cache_config: crate::config::CacheConfig,
+ tool_filter: crate::toolfilter::ToolFilter,
+ ontology_dirs: Vec<std::path::PathBuf>,
) -> Self {
let lineage = crate::lineage::LineageLog::with_governance_webhook(db.clone(), governance_webhook.clone());
let session_id = lineage.new_session();
@@ -146,6 +175,7 @@ impl OpenOntologiesServer {
session_id,
governance_webhook,
registry,
+ ontology_dirs: Arc::new(ontology_dirs),
#[cfg(feature = "embeddings")]
vecstore,
#[cfg(feature = "embeddings")]
@@ -258,6 +288,130 @@ impl OpenOntologiesServer {
}
}
+ #[tool(name = "onto_repo_list", description = "List RDF/OWL files in the configured ontology repository directories ([general] ontology_dirs). Returns metadata for each candidate file (path, name, size, mtime, is_cached, is_active). Use this in containerized/server deployments to discover ontologies without knowing their paths in advance. Optional `dir` (must be under a configured repo dir), `recursive`, `glob`, `limit`, `offset` filters.")]
+ fn onto_repo_list(&self, Parameters(input): Parameters<OntoRepoListInput>) -> String {
+ let repos = self.ontology_dirs.as_ref();
+ if repos.is_empty() {
+ return r#"{"error":"no ontology_dirs configured; set [general] ontology_dirs in config.toml or OPEN_ONTOLOGIES_ONTOLOGY_DIRS"}"#.to_string();
+ }
+ let recursive = input.recursive.unwrap_or(false);
+ let limit = input.limit.unwrap_or(1000);
+ let offset = input.offset.unwrap_or(0);
+
+ let entries = if let Some(dir) = input.dir.as_deref() {
+ match crate::repo::resolve_within_repos(dir, repos) {
+ Ok((start, repo_root)) => crate::repo::list_one(&repo_root, &start, recursive),
+ Err(e) => {
+ return format!(
+ r#"{{"error":"{}"}}"#,
+ e.to_string().replace('"', "'")
+ );
+ }
+ }
+ } else {
+ crate::repo::list_all(repos, recursive)
+ };
+
+ let filtered: Vec<&crate::repo::RepoEntry> = entries
+ .iter()
+ .filter(|e| {
+ if let Some(g) = input.glob.as_deref() {
+ let name = e
+ .path
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("");
+ crate::repo::glob_match(g, name)
+ } else {
+ true
+ }
+ })
+ .collect();
+ let total = filtered.len();
+
+ // Snapshot cached names + currently active name for is_cached / is_active.
+ let cached_names: std::collections::HashSet<String> = self
+ .registry
+ .cache()
+ .list()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|e| e.name)
+ .collect();
+ let active_name = self
+ .registry
+ .status()
+ .get("active")
+ .and_then(|a| a.get("name"))
+ .and_then(|n| n.as_str())
+ .map(|s| s.to_string());
+
+ let items: Vec<serde_json::Value> = filtered
+ .into_iter()
+ .skip(offset)
+ .take(limit)
+ .map(|e| {
+ serde_json::json!({
+ "path": e.path.to_string_lossy(),
+ "relative": e.relative.to_string_lossy(),
+ "repo_dir": e.repo_dir.to_string_lossy(),
+ "name": e.name,
+ "size": e.size,
+ "mtime": e.mtime_secs,
+ "is_cached": cached_names.contains(&e.name),
+ "is_active": active_name.as_deref() == Some(e.name.as_str()),
+ })
+ })
+ .collect();
+
+ let repo_dirs: Vec<String> = repos
+ .iter()
+ .map(|p| p.to_string_lossy().into_owned())
+ .collect();
+
+ serde_json::json!({
+ "ok": true,
+ "ontology_dirs": repo_dirs,
+ "total": total,
+ "offset": offset,
+ "limit": limit,
+ "count": items.len(),
+ "items": items,
+ })
+ .to_string()
+ }
+
+ #[tool(name = "onto_repo_load", description = "Load an ontology from one of the configured repository directories ([general] ontology_dirs) into the active store. The `name` argument can be a bare file stem, a relative path, or an absolute path inside a configured repo. Reuses the same compile-cache / TTL-eviction path as `onto_load`.")]
+ async fn onto_repo_load(&self, Parameters(input): Parameters<OntoRepoLoadInput>) -> String {
+ let repos = self.ontology_dirs.as_ref();
+ let path = match crate::repo::resolve_load_target(&input.name, repos) {
+ Ok(p) => p,
+ Err(e) => {
+ return format!(
+ r#"{{"error":"{}"}}"#,
+ e.to_string().replace('"', "'")
+ );
+ }
+ };
+ let opts = crate::registry::LoadOptions {
+ name: input.registry_name,
+ auto_refresh: input.auto_refresh.unwrap_or(false),
+ force_recompile: input.force_recompile.unwrap_or(false),
+ };
+ match self.registry.load_file(&path.to_string_lossy(), opts) {
+ Ok(res) => serde_json::json!({
+ "ok": true,
+ "triples_loaded": res.triple_count,
+ "path": res.source_path,
+ "name": res.name,
+ "origin": res.origin,
+ "cache_path": res.cache_path,
+ })
+ .to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
+ }
+ }
+
#[tool(name = "onto_query", description = "Run a SPARQL query against the loaded ontology store. If the active ontology has been evicted from memory (idle TTL), it is transparently reloaded from the compile cache before the query runs.")]
async fn onto_query(&self, Parameters(input): Parameters<OntoQueryInput>) -> String {
if let Err(e) = self.registry.ensure_loaded() {
diff --git a/src/toolfilter.rs b/src/toolfilter.rs
index ff33b7e2..86533e65 100644
--- a/src/toolfilter.rs
+++ b/src/toolfilter.rs
@@ -141,6 +141,7 @@ pub fn expand_group(name: &str) -> &'static [&'static str] {
"onto_lineage",
"onto_cache_status",
"onto_cache_list",
+ "onto_repo_list",
"onto_dl_check",
"onto_dl_explain",
"onto_search",
@@ -165,6 +166,7 @@ pub fn expand_group(name: &str) -> &'static [&'static str] {
"onto_unload",
"onto_recompile",
"onto_cache_remove",
+ "onto_repo_load",
],
// Tools that change governance / lifecycle state.
"governance" => &[
diff --git a/tests/repo_test.rs b/tests/repo_test.rs
new file mode 100644
index 00000000..1e6f8560
--- /dev/null
+++ b/tests/repo_test.rs
@@ -0,0 +1,205 @@
+//! Integration tests for the on-disk ontology repository helpers
+//! (`src/repo.rs`) used by the `onto_repo_list` and `onto_repo_load` MCP
+//! tools.
+
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use open_ontologies::config::{resolve_ontology_dirs, Config};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::registry::{LoadOptions, OntologyRegistry};
+use open_ontologies::repo;
+use open_ontologies::state::StateDb;
+
+const SAMPLE_TTL: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/test#> .
+
+ex:Animal a owl:Class ; rdfs:label "Animal" .
+ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal ; rdfs:label "Dog" .
+"#;
+
+const SAMPLE_TTL_B: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/other#> .
+
+ex:Vehicle a owl:Class ; rdfs:label "Vehicle" .
+"#;
+
+fn setup_repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
+ let tmp = tempfile::tempdir().unwrap();
+ let repo = tmp.path().join("ttl_data");
+ std::fs::create_dir_all(&repo).unwrap();
+ let a = repo.join("animals.ttl");
+ let b = repo.join("vehicles.ttl");
+ std::fs::write(&a, SAMPLE_TTL).unwrap();
+ std::fs::write(&b, SAMPLE_TTL_B).unwrap();
+ // A non-RDF file that should be ignored.
+ std::fs::write(repo.join("README.md"), "not rdf").unwrap();
+ // A nested file to exercise the recursive flag.
+ let nested = repo.join("sub");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::fs::write(nested.join("nested.ttl"), SAMPLE_TTL).unwrap();
+ (tmp, repo, a)
+}
+
+#[test]
+fn list_one_filters_to_rdf_extensions() {
+ let (_tmp, repo, _) = setup_repo();
+ let entries = repo::list_one(&repo, &repo, false);
+ let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
+ assert!(names.contains(&"animals"));
+ assert!(names.contains(&"vehicles"));
+ assert!(!names.contains(&"README"), "non-RDF file should be skipped");
+ // Non-recursive: nested.ttl excluded.
+ assert!(!names.contains(&"nested"));
+}
+
+#[test]
+fn list_one_recursive_includes_nested() {
+ let (_tmp, repo, _) = setup_repo();
+ let entries = repo::list_one(&repo, &repo, true);
+ let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
+ assert!(names.contains(&"nested"));
+}
+
+#[test]
+fn glob_filters_filename_only() {
+ assert!(repo::glob_match("*.ttl", "foo.ttl"));
+ assert!(!repo::glob_match("*.ttl", "foo.nt"));
+ assert!(repo::glob_match("a*", "abc"));
+}
+
+#[test]
+fn resolve_load_target_by_bare_stem() {
+ let (_tmp, repo, expected) = setup_repo();
+ let path = repo::resolve_load_target("animals", &[repo.clone()]).unwrap();
+ assert_eq!(
+ std::fs::canonicalize(&path).unwrap(),
+ std::fs::canonicalize(&expected).unwrap()
+ );
+}
+
+#[test]
+fn resolve_load_target_by_relative_path() {
+ let (_tmp, repo, _) = setup_repo();
+ let path = repo::resolve_load_target("sub/nested.ttl", &[repo.clone()]).unwrap();
+ assert!(path.ends_with("sub/nested.ttl") || path.ends_with("sub\\nested.ttl"));
+}
+
+#[test]
+fn resolve_load_target_rejects_outside_path() {
+ let (_tmp, repo, _) = setup_repo();
+ let outside = tempfile::tempdir().unwrap();
+ let outside_file = outside.path().join("evil.ttl");
+ std::fs::write(&outside_file, SAMPLE_TTL).unwrap();
+ let err = repo::resolve_load_target(outside_file.to_str().unwrap(), &[repo.clone()])
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("outside") || err.contains("no file"), "got: {}", err);
+}
+
+#[test]
+fn resolve_load_target_ambiguous_returns_error() {
+ let tmp = tempfile::tempdir().unwrap();
+ let r1 = tmp.path().join("r1");
+ let r2 = tmp.path().join("r2");
+ std::fs::create_dir_all(&r1).unwrap();
+ std::fs::create_dir_all(&r2).unwrap();
+ std::fs::write(r1.join("dup.ttl"), SAMPLE_TTL).unwrap();
+ std::fs::write(r2.join("dup.ttl"), SAMPLE_TTL).unwrap();
+ let err = repo::resolve_load_target("dup", &[r1, r2])
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("ambiguous"), "got: {}", err);
+}
+
+#[test]
+fn resolve_within_repos_rejects_traversal() {
+ let (_tmp, repo, _) = setup_repo();
+ let err = repo::resolve_within_repos("/etc", &[repo.clone()])
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("not under"), "got: {}", err);
+}
+
+#[test]
+fn resolve_within_repos_accepts_subdir() {
+ let (_tmp, repo, _) = setup_repo();
+ let (resolved, repo_root) = repo::resolve_within_repos("sub", &[repo.clone()]).unwrap();
+ assert!(resolved.ends_with("sub"));
+ assert_eq!(
+ std::fs::canonicalize(&repo_root).unwrap(),
+ std::fs::canonicalize(&repo).unwrap()
+ );
+}
+
+#[test]
+fn registry_loads_path_resolved_from_repo() {
+ // End-to-end: simulate what `onto_repo_load` does — resolve a name against
+ // the configured repo dirs, then call `registry.load_file`.
+ let (_tmp, repo, _) = setup_repo();
+ let state_dir = tempfile::tempdir().unwrap();
+ let cache_dir = state_dir.path().join("cache");
+ let db = StateDb::open(&state_dir.path().join("state.db")).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = open_ontologies::config::CacheConfig {
+ enabled: true,
+ dir: cache_dir.to_string_lossy().into_owned(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ };
+ let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
+
+ let path = repo::resolve_load_target("vehicles", &[repo.clone()]).unwrap();
+ let res = registry
+ .load_file(&path.to_string_lossy(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(res.name, "vehicles");
+ assert!(res.triple_count > 0);
+}
+
+#[test]
+fn config_alias_data_dirs_works() {
+ let toml = r#"
+[general]
+data_dir = "/tmp/state"
+data_dirs = ["/tmp/a", "/tmp/b"]
+"#;
+ let cfg: Config = toml::from_str(toml).unwrap();
+ assert_eq!(cfg.general.ontology_dirs, vec!["/tmp/a", "/tmp/b"]);
+}
+
+#[test]
+fn config_canonical_ontology_dirs_works() {
+ let toml = r#"
+[general]
+data_dir = "/tmp/state"
+ontology_dirs = ["./ttl_data"]
+"#;
+ let cfg: Config = toml::from_str(toml).unwrap();
+ assert_eq!(cfg.general.ontology_dirs, vec!["./ttl_data"]);
+}
+
+#[test]
+fn resolve_ontology_dirs_dedupes_and_expands_tilde() {
+ // Ensure the env var is unset for this test (other tests may set it).
+ // Safe in single-threaded test flow; cargo test in this crate is the
+ // default threadpool but env reads happen synchronously in this fn.
+ // Use a unique env-cleared scope to be safe.
+ let prev = std::env::var("OPEN_ONTOLOGIES_ONTOLOGY_DIRS").ok();
+ // SAFETY: tests touching process env must accept the inherent unsafety
+ // of process-wide globals; this test is gated by the env var name.
+ unsafe { std::env::remove_var("OPEN_ONTOLOGIES_ONTOLOGY_DIRS") };
+ let tmp = tempfile::tempdir().unwrap();
+ let p = tmp.path().to_string_lossy().into_owned();
+ let resolved =
+ resolve_ontology_dirs(&[p.clone(), p.clone(), "".to_string()]);
+ assert_eq!(resolved.len(), 1, "duplicates should be removed");
+ if let Some(v) = prev {
+ unsafe { std::env::set_var("OPEN_ONTOLOGIES_ONTOLOGY_DIRS", v) };
+ }
+}