Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(mcp): resolve the embedder API key from persisted config (#1230)

Raghav Chamadiya45b007bd96b8
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index ffb9d09cf..252bd4801 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -65,6 +65,77 @@ def _configured_embedder_name() -> str:
return ""
+# Keyed embedders and the env vars each reads its credential from. The first
+# entry is the canonical name the CLI persists under; the rest are accepted
+# aliases. Embedders outside this map (ollama, mock, custom) need no API key.
+_EMBEDDER_KEY_ENV: dict[str, tuple[str, ...]] = {
+ "openai": ("OPENAI_API_KEY",),
+ "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"),
+ "openrouter": ("OPENROUTER_API_KEY",),
+}
+
+
+def _persisted_embedder_key(name: str) -> str | None:
+ """Recover the configured embedder's API key from where the CLI persists it.
+
+ ``repowise mcp`` loads ``<repo>/.repowise/.env`` before starting, but that
+ covers only the repo it was pointed at: a workspace serves sibling repos
+ whose ``.env`` is never read, and embedded callers reach :func:`run_mcp`
+ without going through the CLI at all. ``repowise serve`` already falls back
+ to the ``embedder_api_key`` saved in ``~/.repowise/config.yaml``. Without
+ the same fallback here the server builds a ``MockEmbedder`` and queries a
+ real index with vectors that cannot match it — semantic search silently
+ degrades to full-text-only.
+
+ Order: the served repo's ``.repowise/.env`` first, then the global config.
+ Returns ``None`` when the embedder needs no key or none is persisted.
+ """
+ from pathlib import Path
+
+ env_vars = _EMBEDDER_KEY_ENV.get(name)
+ if not env_vars:
+ return None
+ canonical = env_vars[0]
+
+ if _state._repo_path:
+ try:
+ # Reuse the reader get_answer already uses for the LLM credential,
+ # rather than a third copy of .env parsing.
+ from repowise.server.mcp_server.tool_answer.synthesis import (
+ _load_repo_provider_config,
+ )
+
+ _, _, overlay = _load_repo_provider_config(Path(_state._repo_path))
+ for var in env_vars:
+ if overlay.get(var):
+ return overlay[var]
+ except Exception:
+ _log.debug("Failed to read repo .env for embedder key", exc_info=True)
+
+ try:
+ cfg_path = Path.home() / ".repowise" / "config.yaml"
+ if cfg_path.is_file():
+ import yaml # type: ignore[import-untyped]
+
+ cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}
+ # Only honour the saved key when it belongs to the embedder being
+ # resolved — handing an openai key to gemini fails confusingly.
+ if (cfg.get("embedder") or "").strip().lower() == name:
+ key = str(cfg.get("embedder_api_key") or "").strip()
+ if key:
+ _log.info(
+ "Embedder key for '%s' recovered from ~/.repowise/config.yaml "
+ "(%s not set in the MCP server's environment).",
+ name,
+ canonical,
+ )
+ return key
+ except Exception:
+ _log.debug("Failed to read global config for embedder key", exc_info=True)
+
+ return None
+
+
def _embedder_kwargs(name: str) -> dict[str, Any]:
"""Map repowise embedding env vars onto an embedder's constructor kwargs.
@@ -72,6 +143,10 @@ def _embedder_kwargs(name: str) -> dict[str, Any]:
that accepts a ``model`` arg; ``REPOWISE_EMBEDDING_DIMS`` is gemini-specific
(its constructor exposes ``output_dimensionality``). Anything not set here
falls through to the embedder's own defaults.
+
+ When the embedder needs an API key and the environment has none, the key is
+ recovered from the repo/global config so the server matches the index it
+ was pointed at instead of falling back to mock vectors.
"""
kwargs: dict[str, Any] = {}
model = os.environ.get("REPOWISE_EMBEDDING_MODEL")
@@ -80,6 +155,12 @@ def _embedder_kwargs(name: str) -> dict[str, Any]:
if name == "gemini":
dims = os.environ.get("REPOWISE_EMBEDDING_DIMS")
kwargs["output_dimensionality"] = int(dims) if dims else 768
+
+ env_vars = _EMBEDDER_KEY_ENV.get(name, ())
+ if env_vars and not any(os.environ.get(var) for var in env_vars):
+ key = _persisted_embedder_key(name)
+ if key:
+ kwargs["api_key"] = key
return kwargs
diff --git a/tests/unit/server/mcp/test_embedder_resolution.py b/tests/unit/server/mcp/test_embedder_resolution.py
index f9e402097..c796156d7 100644
--- a/tests/unit/server/mcp/test_embedder_resolution.py
+++ b/tests/unit/server/mcp/test_embedder_resolution.py
@@ -12,6 +12,8 @@ the shared registry, so openrouter and custom-registered embedders are honoured
from __future__ import annotations
+from pathlib import Path
+
import pytest
from repowise.core.providers.embedding.base import MockEmbedder
@@ -36,12 +38,21 @@ _EMBEDDER_ENV_VARS = (
@pytest.fixture(autouse=True)
-def _clean_env_and_state(monkeypatch):
- """Strip embedder env vars + reset status so each test starts from scratch."""
+def _clean_env_and_state(monkeypatch, tmp_path):
+ """Strip embedder env vars + reset status so each test starts from scratch.
+
+ ``Path.home()`` is redirected at an empty directory too: resolution falls
+ back to the ``embedder_api_key`` saved in ``~/.repowise/config.yaml``, so a
+ developer who has one would otherwise see the "missing key" tests resolve a
+ real embedder and fail locally while passing in CI.
+ """
for var in _EMBEDDER_ENV_VARS:
monkeypatch.delenv(var, raising=False)
monkeypatch.setattr(_state, "_repo_path", None, raising=False)
monkeypatch.setattr(_state, "_embedder_status", None, raising=False)
+ empty_home = tmp_path / "empty-home"
+ empty_home.mkdir()
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: empty_home))
yield
_state._embedder_status = None
@@ -160,6 +171,91 @@ def test_config_yaml_embedder_is_read(monkeypatch, tmp_path):
assert _state._embedder_status["degraded"] is True
+def test_repo_dotenv_supplies_missing_embedder_key(monkeypatch, tmp_path):
+ """The key persisted in the repo's .repowise/.env is used when env has none.
+
+ `repowise mcp` loads that file for the repo it is pointed at, but workspace
+ siblings and embedded run_mcp() callers never get it — without this fallback
+ the server queries an openai-embedded index with mock vectors.
+ """
+ from repowise.core.providers.embedding.openai import OpenAIEmbedder
+
+ repo_dir = tmp_path / "repo"
+ (repo_dir / ".repowise").mkdir(parents=True)
+ (repo_dir / ".repowise" / "config.yaml").write_text("embedder: openai\n", encoding="utf-8")
+ (repo_dir / ".repowise" / ".env").write_text(
+ "OPENAI_API_KEY=sk-from-dotenv\n", encoding="utf-8"
+ )
+ monkeypatch.setattr(_state, "_repo_path", str(repo_dir))
+
+ embedder = _server._resolve_embedder()
+
+ assert isinstance(embedder, OpenAIEmbedder)
+ assert _state._embedder_status == {
+ "active": "openai",
+ "requested": "openai",
+ "degraded": False,
+ }
+
+
+def test_global_config_supplies_missing_embedder_key(monkeypatch, tmp_path):
+ """`repowise serve` restores embedder_api_key from ~/.repowise/config.yaml —
+ the MCP server must resolve the same credential from the same place."""
+ from repowise.core.providers.embedding.openai import OpenAIEmbedder
+
+ home = tmp_path / "home"
+ (home / ".repowise").mkdir(parents=True)
+ (home / ".repowise" / "config.yaml").write_text(
+ "embedder: openai\nembedder_api_key: sk-from-global\n", encoding="utf-8"
+ )
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")
+
+ embedder = _server._resolve_embedder()
+
+ assert isinstance(embedder, OpenAIEmbedder)
+ assert _state._embedder_status["degraded"] is False
+
+
+def test_global_config_key_not_used_for_a_different_embedder(monkeypatch, tmp_path):
+ """A saved openai key must not be handed to gemini — that fails confusingly."""
+ home = tmp_path / "home"
+ (home / ".repowise").mkdir(parents=True)
+ (home / ".repowise" / "config.yaml").write_text(
+ "embedder: openai\nembedder_api_key: sk-from-global\n", encoding="utf-8"
+ )
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "gemini")
+
+ embedder = _server._resolve_embedder()
+
+ assert isinstance(embedder, MockEmbedder)
+ assert _state._embedder_status["degraded"] is True
+
+
+def test_process_env_key_wins_over_persisted(monkeypatch, tmp_path):
+ """An explicitly exported key stays authoritative over the persisted one."""
+ from repowise.core.providers.embedding.openai import OpenAIEmbedder
+
+ repo_dir = tmp_path / "repo"
+ (repo_dir / ".repowise").mkdir(parents=True)
+ (repo_dir / ".repowise" / ".env").write_text("OPENAI_API_KEY=sk-persisted\n", encoding="utf-8")
+ monkeypatch.setattr(_state, "_repo_path", str(repo_dir))
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-exported")
+
+ embedder = _server._resolve_embedder()
+
+ assert isinstance(embedder, OpenAIEmbedder)
+ assert embedder._api_key == "sk-exported"
+
+
+def test_keyless_embedder_needs_no_persisted_lookup(monkeypatch):
+ """Embedders outside the keyed map resolve without touching the config files."""
+ assert _server._persisted_embedder_key("ollama") is None
+ assert _server._persisted_embedder_key("mock") is None
+
+
def test_build_meta_surfaces_degraded_embedder(monkeypatch):
"""A degraded embedder shows up in the _meta envelope so callers can detect it."""
monkeypatch.setattr(