Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): read the doctor backends from the environment, not just the config (#1934)

Kevin7e1c1ccfb38b
diff --git a/semantica/cli.py b/semantica/cli.py
index b05fec52..8bf5eec7 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -556,10 +556,7 @@ def _show_startup(cli_ctx: CLIContext) -> None:
return
cfg = cli_ctx.config.to_dict()
graph_store = _resolve_graph_backend(cli_ctx)
- vector_store = (
- cli_ctx.vector_store_backend
- or cfg.get("vector_store", {}).get("backend", "faiss")
- )
+ vector_store = _configured_vector_backend(cli_ctx) or _DEFAULT_VECTOR_BACKEND
profile = cfg.get("profile", "default")
console.print()
@@ -1005,14 +1002,73 @@ def doctor(cli_ctx: CLIContext, local_json: bool, deep_embeddings: bool) -> None
return f"{backend} reachable"
checks.append(_check("Graph store", _graph, hint="run 'semantica store list' to see configured backends"))
- # Vector store
+ # Vector store: the one CLI commands build (--vector-store or
+ # vector_store.backend). The MCP server's own store is checked below.
+ configured_vector = _configured_vector_backend(cli_ctx)
+ mcp_configured = _mcp_stores_configured()
+
def _vector() -> str:
- cfg = cli_ctx.config.to_dict()
- backend = cli_ctx.vector_store_backend or cfg.get("vector_store", {}).get("backend", "faiss")
+ backend = configured_vector or _DEFAULT_VECTOR_BACKEND
if backend == "faiss":
import faiss # noqa: F401
+ elif backend == "sqlite":
+ _probe_sqlite_vec()
+ return "sqlite-vec loaded"
return f"{backend} importable"
- checks.append(_check("Vector store", _vector, hint="pip install semantica[vectorstore-…]"))
+ vector_row = _check(
+ "Vector store", _vector, hint="pip install semantica[vectorstore-…]"
+ )
+ if vector_row[1] == "fail" and not configured_vector and mcp_configured:
+ # Nothing asked the CLI for faiss and this deployment configures
+ # the MCP server instead, so the missing default is not an error
+ # for it — only for CLI vector commands (#1818).
+ vector_row = (
+ "Vector store", "warn", f"{vector_row[2]} (CLI default)",
+ "set vector_store.backend to use CLI vector commands",
+ )
+ checks.append(vector_row)
+
+ # MCP server stores (#1818): configured only through the environment
+ # and resolved by the server's own session helpers, so this reports
+ # exactly what `semantica mcp` would build.
+ def _mcp_vector() -> str:
+ from semantica_mcp.mcp.session import resolve_vector_backend
+
+ backend, _ = resolve_vector_backend()
+ if backend == "sqlite":
+ _probe_sqlite_vec()
+ return "sqlite-vec loaded"
+ return backend
+
+ def _mcp_graph() -> str:
+ from semantica_mcp.mcp.session import kg_file_to_load, kg_path
+ from .context import ContextGraph
+
+ if not kg_path():
+ return "in-memory, not persisted (SEMANTICA_KG_PATH unset)"
+ path = kg_file_to_load()
+ if path is None:
+ return "new graph, created on first save"
+ graph = ContextGraph()
+ try:
+ graph.load_from_file(path)
+ except Exception as exc:
+ # The server would start empty and refuse to save over it.
+ raise RuntimeError(
+ f"cannot load {path}: {exc}; persistence would be disabled"
+ ) from exc
+ return f"{len(graph.get_nodes_by_label('decision'))} decision(s)"
+
+ if mcp_configured:
+ checks.append(_check(
+ "MCP vector store", _mcp_vector,
+ hint="check SEMANTICA_VECTOR_*; sqlite needs "
+ "pip install 'semantica[vectorstore-sqlite]'",
+ ))
+ checks.append(_check(
+ "MCP graph", _mcp_graph,
+ hint="fix or move the file at SEMANTICA_KG_PATH",
+ ))
# Embedding backends (#994): `doctor` used to report all green while
# every local embedding backend was non-functional — import success
@@ -1325,6 +1381,19 @@ _LOCK_TIMEOUT_SECONDS = 10.0
# `semantica init` offers memory as its default and ContextGraph serves it
# without any server, so it is also the fallback when nothing is configured.
_DEFAULT_GRAPH_BACKEND = MEMORY_GRAPH_BACKEND
+# VectorStore's own default: what CLI vector commands build when neither
+# --vector-store nor vector_store.backend is set.
+_DEFAULT_VECTOR_BACKEND = "faiss"
+# Environment that configures the MCP server's stores
+# (semantica_mcp/mcp/session.py). It never changes what the CLI builds, so
+# ``doctor`` reports it in rows of its own rather than folding it into the
+# CLI's vector and graph checks (#1818).
+_MCP_STORE_ENV_VARS = (
+ "SEMANTICA_VECTOR_BACKEND",
+ "SEMANTICA_VECTOR_DB_PATH",
+ "SEMANTICA_VECTOR_PATH",
+ "SEMANTICA_KG_PATH",
+)
def _resolve_graph_backend(cli_ctx: CLIContext) -> str:
@@ -1340,6 +1409,33 @@ def _resolve_graph_backend(cli_ctx: CLIContext) -> str:
)
+def _configured_vector_backend(cli_ctx: CLIContext) -> Optional[str]:
+ """The ``--vector-store`` flag or ``vector_store.backend``; None if unset."""
+ return cli_ctx.vector_store_backend or cli_ctx.config.to_dict().get(
+ "vector_store", {}
+ ).get("backend")
+
+
+def _mcp_stores_configured() -> bool:
+ """True when the environment configures the MCP server's stores."""
+ return any(os.environ.get(var, "").strip() for var in _MCP_STORE_ENV_VARS)
+
+
+def _probe_sqlite_vec() -> None:
+ """Raise unless the sqlite-vec extension actually loads.
+
+ ``SQLITE_VEC_AVAILABLE`` is a ``find_spec`` probe: it proves the package is
+ discoverable, not that the native extension loads. Building a throwaway
+ in-memory store runs the store's real load path, so a broken install fails
+ here rather than on first use.
+ """
+ from .vector_store.sqlite_vec_store import SQLITE_VEC_AVAILABLE, SQLiteVecStore
+
+ if not SQLITE_VEC_AVAILABLE:
+ raise ImportError("sqlite-vec is not installed")
+ SQLiteVecStore(db_path=":memory:", table_name="doctor_probe", dimension=1).close()
+
+
def _uses_memory_graph(cli_ctx: CLIContext) -> bool:
"""True when decisions and exports are served by an in-process ContextGraph.
diff --git a/semantica_mcp/mcp/session.py b/semantica_mcp/mcp/session.py
index 9aedc325..508664fc 100644
--- a/semantica_mcp/mcp/session.py
+++ b/semantica_mcp/mcp/session.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import logging
import os
-from typing import Any, Optional
+from typing import Any, Dict, Optional, Tuple
log = logging.getLogger("semantica.mcp.session")
@@ -46,27 +46,42 @@ def get_graph() -> Any:
_graph = ContextGraph(advanced_analytics=True)
_load_ok = True # default: safe to persist
- kg_path = os.environ.get("SEMANTICA_KG_PATH", "").strip()
- if kg_path and os.path.exists(kg_path):
- # Only attempt to load if the file has content. An empty file
- # means the path was just created (e.g. a fresh tempfile) and
- # should be treated as "start with empty graph" rather than a
- # corrupt-file failure.
- if os.path.getsize(kg_path) > 0:
- try:
- _graph.load_from_file(kg_path)
- log.info("Graph loaded from %s", kg_path)
- except Exception as exc:
- log.warning(
- "Could not load graph from %s: %s — persistence disabled "
- "to protect existing data; restart the server to retry.",
- kg_path, exc,
- )
- _load_ok = False # do not overwrite the original file
+ path = kg_file_to_load()
+ if path:
+ try:
+ _graph.load_from_file(path)
+ log.info("Graph loaded from %s", path)
+ except Exception as exc:
+ log.warning(
+ "Could not load graph from %s: %s — persistence disabled "
+ "to protect existing data; restart the server to retry.",
+ path, exc,
+ )
+ _load_ok = False # do not overwrite the original file
return _graph
+def kg_path() -> str:
+ """Return the configured ``SEMANTICA_KG_PATH``, or ``""`` when unset."""
+ return os.environ.get("SEMANTICA_KG_PATH", "").strip()
+
+
+def kg_file_to_load() -> Optional[str]:
+ """Return the graph file ``get_graph`` will load, or None to start empty.
+
+ A missing file starts an empty graph that is created on the first save.
+ An empty file means the path was just created (e.g. a fresh tempfile)
+ and is likewise treated as "start with empty graph" rather than a
+ corrupt-file failure. Shared with ``semantica doctor`` so its check
+ follows the same rules as the server (#1818).
+ """
+ path = kg_path()
+ if path and os.path.exists(path) and os.path.getsize(path) > 0:
+ return path
+ return None
+
+
def get_embedder() -> Any:
"""
Return the shared EmbeddingGenerator instance, creating it on first call.
@@ -87,6 +102,37 @@ def get_embedder() -> Any:
return _embedder
+def resolve_vector_backend() -> Tuple[str, Dict[str, Any]]:
+ """Return the backend and store config ``get_vector_store`` will use.
+
+ Reads and validates the environment without building a store or an
+ embedder, so ``semantica doctor`` can report exactly what this server
+ would do instead of re-implementing the rules (#1818). The returned
+ config does not yet include ``dimension``, which comes from the embedder.
+
+ Raises:
+ ValueError: The backend is unsupported, or ``sqlite`` is selected
+ without ``SEMANTICA_VECTOR_DB_PATH``.
+ """
+ backend = os.environ.get("SEMANTICA_VECTOR_BACKEND", "inmemory").strip().lower()
+ if backend not in SUPPORTED_VECTOR_BACKENDS:
+ raise ValueError(
+ f"SEMANTICA_VECTOR_BACKEND={backend!r} is not supported by the "
+ "MCP retrieval tools; supported backends: "
+ + ", ".join(SUPPORTED_VECTOR_BACKENDS)
+ )
+ config: Dict[str, Any] = {}
+ if backend == "sqlite":
+ db_path = os.environ.get("SEMANTICA_VECTOR_DB_PATH", "").strip()
+ if not db_path:
+ raise ValueError(
+ "SEMANTICA_VECTOR_BACKEND=sqlite requires "
+ "SEMANTICA_VECTOR_DB_PATH to point at the database file"
+ )
+ config["db_path"] = db_path
+ return backend, config
+
+
def get_vector_store() -> Any:
"""
Return the shared VectorStore instance, creating it on first call.
@@ -110,22 +156,7 @@ def get_vector_store() -> Any:
if _vector_store is None:
from semantica.vector_store import VectorStore
- backend = os.environ.get("SEMANTICA_VECTOR_BACKEND", "inmemory").strip().lower()
- if backend not in SUPPORTED_VECTOR_BACKENDS:
- raise ValueError(
- f"SEMANTICA_VECTOR_BACKEND={backend!r} is not supported by the "
- "MCP retrieval tools; supported backends: "
- + ", ".join(SUPPORTED_VECTOR_BACKENDS)
- )
- config: dict = {}
- if backend == "sqlite":
- db_path = os.environ.get("SEMANTICA_VECTOR_DB_PATH", "").strip()
- if not db_path:
- raise ValueError(
- "SEMANTICA_VECTOR_BACKEND=sqlite requires "
- "SEMANTICA_VECTOR_DB_PATH to point at the database file"
- )
- config["db_path"] = db_path
+ backend, config = resolve_vector_backend()
# VectorStore defaults to dimension 768, which does not match the
# default embedding model (all-MiniLM-L6-v2 = 384, hash fallback
# = 128). Always derive it from the embedder so store and
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index 3bd5df78..9eeb6118 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -18,6 +18,7 @@ import os
import time
import re
import stat
+import sys
import tarfile
import types
from typing import Any
@@ -4705,6 +4706,212 @@ class TestDoctorEmbeddingHintsAndEnv:
assert "hash fallback" in st["note"], "padded/caps env value must enable deep mode"
+class TestDoctorBackendEnvResolution:
+ """#1818: doctor must report the MCP server's stores, which are configured
+ only through ``SEMANTICA_VECTOR_*`` / ``SEMANTICA_KG_PATH``.
+
+ Those variables never change what CLI commands build, so they get their own
+ rows resolved by the server's session helpers instead of being folded into
+ the CLI's vector and graph checks.
+ """
+
+ _MCP_ENV = (
+ "SEMANTICA_VECTOR_BACKEND",
+ "SEMANTICA_VECTOR_DB_PATH",
+ "SEMANTICA_VECTOR_PATH",
+ "SEMANTICA_KG_PATH",
+ )
+
+ @pytest.fixture(autouse=True)
+ def _clean_env(self, monkeypatch):
+ for var in self._MCP_ENV:
+ monkeypatch.delenv(var, raising=False)
+
+ @pytest.fixture
+ def cfg(self, tmp_path):
+ # graph_db.path keeps the CLI graph row off the real ~/.semantica.
+ def _write(extra=""):
+ path = tmp_path / "cfg.yaml"
+ path.write_text(
+ "graph_db:\n backend: memory\n"
+ f" path: {tmp_path / 'cli_graph.json'}\n" + extra
+ )
+ return str(path)
+
+ return _write
+
+ def _checks(self, runner, config):
+ args = ["--config", config, "doctor", "--json"]
+ result = runner.invoke(cli_module.main, args)
+ _ok(result)
+ return {c["check"]: c for c in json.loads(result.output)}
+
+ @staticmethod
+ def _without_faiss(monkeypatch):
+ monkeypatch.setitem(sys.modules, "faiss", None)
+
+ @staticmethod
+ def _with_faiss(monkeypatch):
+ monkeypatch.setitem(sys.modules, "faiss", types.ModuleType("faiss"))
+
+ @staticmethod
+ def _sqlite_vec_loads(monkeypatch):
+ monkeypatch.setattr(cli_module, "_probe_sqlite_vec", lambda: None)
+
+ @staticmethod
+ def _save_graph_with_one_decision(path):
+ from semantica.context import ContextGraph
+
+ graph = ContextGraph()
+ graph.record_decision(
+ category="vendor_selection",
+ scenario="Pick a vector backend",
+ reasoning="sqlite-vec needs no server",
+ outcome="selected_sqlite",
+ confidence=0.9,
+ )
+ graph.save_to_file(path)
+
+ def test_no_mcp_rows_without_mcp_env(self, runner, cfg):
+ checks = self._checks(runner, cfg())
+ assert "MCP vector store" not in checks
+ assert "MCP graph" not in checks
+
+ def test_reports_the_mcp_sqlite_store(self, runner, cfg, tmp_path, monkeypatch):
+ self._sqlite_vec_loads(monkeypatch)
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", " SQLite ")
+ monkeypatch.setenv("SEMANTICA_VECTOR_DB_PATH", str(tmp_path / "v.db"))
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "ok"
+ assert row["note"] == "sqlite-vec loaded"
+
+ def test_mcp_env_is_read_even_when_init_wrote_a_cli_backend(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ # `semantica init` writes vector_store.backend: faiss by default; that
+ # must neither hide the MCP store nor be replaced by it.
+ self._with_faiss(monkeypatch)
+ self._sqlite_vec_loads(monkeypatch)
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "sqlite")
+ monkeypatch.setenv("SEMANTICA_VECTOR_DB_PATH", str(tmp_path / "v.db"))
+ checks = self._checks(runner, cfg("vector_store:\n backend: faiss\n"))
+ assert checks["MCP vector store"]["note"] == "sqlite-vec loaded"
+ assert checks["Vector store"]["note"] == "faiss importable"
+
+ def test_mcp_vector_defaults_to_inmemory(self, runner, cfg, tmp_path, monkeypatch):
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(tmp_path / "kg.json"))
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "ok"
+ assert row["note"] == "inmemory"
+
+ def test_flags_sqlite_without_a_db_path(self, runner, cfg, monkeypatch):
+ # The server refuses to start this way, so doctor must not pass it.
+ self._sqlite_vec_loads(monkeypatch)
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "sqlite")
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "fail"
+ assert "SEMANTICA_VECTOR_DB_PATH" in row["note"]
+
+ def test_flags_an_unsupported_mcp_backend(self, runner, cfg, monkeypatch):
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "faiss")
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "fail"
+ assert "supported backends: inmemory, sqlite" in row["note"]
+
+ def test_flags_a_missing_sqlite_vec(self, runner, cfg, tmp_path, monkeypatch):
+ import semantica.vector_store.sqlite_vec_store as sqlite_store
+
+ monkeypatch.setattr(sqlite_store, "SQLITE_VEC_AVAILABLE", False)
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "sqlite")
+ monkeypatch.setenv("SEMANTICA_VECTOR_DB_PATH", str(tmp_path / "v.db"))
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "fail"
+ assert "not installed" in row["note"]
+ assert "vectorstore-sqlite" in row["hint"]
+
+ def test_flags_a_sqlite_vec_that_fails_to_load(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ # Discoverable but unloadable must fail: the probe runs the store's
+ # real load path rather than trusting find_spec.
+ import semantica.vector_store.sqlite_vec_store as sqlite_store
+ from semantica.utils.exceptions import ProcessingError
+
+ def _boom(**_):
+ raise ProcessingError("Failed to load sqlite-vec extension: boom")
+
+ monkeypatch.setattr(sqlite_store, "SQLITE_VEC_AVAILABLE", True)
+ monkeypatch.setattr(sqlite_store, "SQLiteVecStore", _boom)
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "sqlite")
+ monkeypatch.setenv("SEMANTICA_VECTOR_DB_PATH", str(tmp_path / "v.db"))
+ row = self._checks(runner, cfg())["MCP vector store"]
+ assert row["status"] == "fail"
+ assert "Failed to load sqlite-vec extension" in row["note"]
+
+ def test_unconfigured_faiss_is_a_warning_for_an_mcp_deployment(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ self._without_faiss(monkeypatch)
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(tmp_path / "kg.json"))
+ row = self._checks(runner, cfg())["Vector store"]
+ assert row["status"] == "warn"
+ assert "CLI default" in row["note"]
+
+ def test_unconfigured_faiss_still_fails_without_mcp_env(
+ self, runner, cfg, monkeypatch
+ ):
+ self._without_faiss(monkeypatch)
+ assert self._checks(runner, cfg())["Vector store"]["status"] == "fail"
+
+ def test_configured_faiss_still_fails_for_an_mcp_deployment(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ self._without_faiss(monkeypatch)
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(tmp_path / "kg.json"))
+ config = cfg("vector_store:\n backend: faiss\n")
+ assert self._checks(runner, config)["Vector store"]["status"] == "fail"
+
+ def test_mcp_graph_counts_decisions_from_kg_path(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ kg = tmp_path / "mcp_graph.json"
+ self._save_graph_with_one_decision(kg)
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(kg))
+ checks = self._checks(runner, cfg())
+ assert checks["MCP graph"]["status"] == "ok"
+ assert checks["MCP graph"]["note"] == "1 decision(s)"
+ # The CLI graph is a different file; it must not report the MCP one.
+ assert checks["Graph store"]["note"] == "memory, 0 decision(s)"
+
+ def test_mcp_graph_accepts_an_empty_or_missing_file(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ # The server starts empty from both, so neither is a failure.
+ empty = tmp_path / "empty.json"
+ empty.write_text("")
+ for path in (empty, tmp_path / "missing.json"):
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(path))
+ row = self._checks(runner, cfg())["MCP graph"]
+ assert row["status"] == "ok"
+ assert row["note"] == "new graph, created on first save"
+
+ def test_mcp_graph_flags_an_unreadable_file(
+ self, runner, cfg, tmp_path, monkeypatch
+ ):
+ kg = tmp_path / "corrupt.json"
+ kg.write_text("{not json")
+ monkeypatch.setenv("SEMANTICA_KG_PATH", str(kg))
+ row = self._checks(runner, cfg())["MCP graph"]
+ assert row["status"] == "fail"
+ assert "persistence would be disabled" in row["note"]
+
+ def test_mcp_graph_without_kg_path_is_in_memory(self, runner, cfg, monkeypatch):
+ monkeypatch.setenv("SEMANTICA_VECTOR_BACKEND", "inmemory")
+ row = self._checks(runner, cfg())["MCP graph"]
+ assert row["status"] == "ok"
+ assert "not persisted" in row["note"]
+
+
class TestDoctorTableLayout:
"""#1428 + Qodo review: doctor table must keep Check labels and Hint text
readable at a normal 80-column terminal.