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.

perf(mcp): import tool modules lazily so one tool does not cost seventeen (#1409)

Raghav Chamadiyaf16190a5a2d6
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 34b73a8f1..6a1e73387 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -13,6 +13,9 @@ Exposes the full repowise wiki as queryable tools via the MCP protocol.
Supports stdio transport (Claude Code, Cursor, Cline), streamable HTTP, and
legacy SSE transport.
+Tool modules load lazily (see :func:`ensure_full_surface`), so importing this
+package, or one tool out of it, does not drag in the other sixteen.
+
Usage:
repowise mcp --transport stdio # for Claude Code / Cursor / Cline
repowise mcp --transport streamable-http # for HTTP clients
@@ -21,64 +24,113 @@ Usage:
from __future__ import annotations
+import importlib
import sys
from typing import Any
-# Attach every tool that registered itself through the shared registry to
-# the FastMCP instance. Idempotent per server, so a second call (e.g. when
-# tests build an isolated mcp) is a no-op against the original mcp.
-from repowise.core.registry import mcp_tool_registry as _mcp_tool_registry
-
-# --- Import submodules in dependency order (triggers tool registration) ---
+# ``_state`` is the one submodule that stays eager: every other module in this
+# package reads its globals, and it defers its own sqlalchemy import so the
+# whole package now costs about what a bare interpreter does.
from repowise.server.mcp_server import _state
-from repowise.server.mcp_server._failure_shield import shield as _failure_shield
-from repowise.server.mcp_server._graph_utils import ( # used by routers/graph.py
- build_visual_context as _build_visual_context,
-)
-from repowise.server.mcp_server._helpers import (
- _build_origin_story,
- _compute_alignment,
- _get_repo,
- _is_path,
-)
-from repowise.server.mcp_server._savings import instrument as _savings_instrument
-from repowise.server.mcp_server._server import (
- create_mcp_server,
- mcp,
- run_mcp,
-)
-from repowise.server.mcp_server._tool_selection import (
- snapshot_full_surface as _snapshot,
-)
-from repowise.server.mcp_server.tool_answer import get_answer
-from repowise.server.mcp_server.tool_architecture import get_architecture
-from repowise.server.mcp_server.tool_blast_radius import get_blast_radius
-from repowise.server.mcp_server.tool_change_risk import get_change_risk
-from repowise.server.mcp_server.tool_conformance import get_conformance
-from repowise.server.mcp_server.tool_context import get_context
-from repowise.server.mcp_server.tool_dead_code import get_dead_code
-from repowise.server.mcp_server.tool_dependency import get_dependency_path
-from repowise.server.mcp_server.tool_flows import get_execution_flows
-from repowise.server.mcp_server.tool_health import get_health
-from repowise.server.mcp_server.tool_overview import get_overview
-from repowise.server.mcp_server.tool_refactoring import generate_refactoring_code
-from repowise.server.mcp_server.tool_repos import list_repos
-from repowise.server.mcp_server.tool_risk import get_risk
-from repowise.server.mcp_server.tool_search import search_codebase
-from repowise.server.mcp_server.tool_symbol import get_symbol
-from repowise.server.mcp_server.tool_why import get_why
-
-# ``middleware`` wraps each tool twice, both layers signature-preserving so the
-# tool schemas are unchanged. The failure shield sits innermost: no exception
-# may escape to FastMCP as a protocol-level isError (an early isError teaches
-# the agent to abandon the server for the whole session). The savings layer
-# wraps it, so shaped error responses are still dead-end-debited in the ledger.
-_mcp_tool_registry.apply(mcp, middleware=lambda fn: _savings_instrument(_failure_shield(fn)))
-
-# Snapshot the full registered surface so per-server tool selection (single-repo
-# vs workspace, config/CLI overrides) can rebuild from it. Selection itself runs
-# later, in create_mcp_server / run_mcp, once the repo path is known.
-_snapshot(mcp)
+
+# ---------------------------------------------------------------------------
+# Lazy attribute surface (PEP 562).
+#
+# This package used to import all 17 tool modules — and through them
+# core.analysis.health, core.generation.onboarding, FastMCP, LanceDB's
+# dependency chain — at package import. That made importing any ONE tool cost
+# ~2.5s, roughly 9x the entire CLI, because a leaf import initialises the
+# parent package first. ``repowise.cli.main`` solved the same shape for its
+# ~35 command modules with lazy registration; this is that fix for the tool
+# surface, so a CLI command adapting a single MCP tool pays for that tool only.
+#
+# Every name below resolves on first attribute access and is then cached on the
+# module, so ``from repowise.server.mcp_server import get_answer`` reads exactly
+# as it did before.
+# ---------------------------------------------------------------------------
+
+#: ``tool name -> submodule``. The full set is what ``ensure_full_surface``
+#: imports; individually they are what a single-tool consumer pays for.
+_TOOL_MODULES: dict[str, str] = {
+ "generate_refactoring_code": "tool_refactoring",
+ "get_answer": "tool_answer",
+ "get_architecture": "tool_architecture",
+ "get_blast_radius": "tool_blast_radius",
+ "get_change_risk": "tool_change_risk",
+ "get_conformance": "tool_conformance",
+ "get_context": "tool_context",
+ "get_dead_code": "tool_dead_code",
+ "get_dependency_path": "tool_dependency",
+ "get_execution_flows": "tool_flows",
+ "get_health": "tool_health",
+ "get_overview": "tool_overview",
+ "get_risk": "tool_risk",
+ "get_symbol": "tool_symbol",
+ "get_why": "tool_why",
+ "list_repos": "tool_repos",
+ "search_codebase": "tool_search",
+}
+
+#: ``exported name -> (submodule, name within it)`` for the non-tool re-exports.
+_LAZY_ATTRS: dict[str, tuple[str, str]] = {
+ "_build_origin_story": ("_helpers", "_build_origin_story"),
+ "_build_visual_context": ("_graph_utils", "build_visual_context"),
+ "_compute_alignment": ("_helpers", "_compute_alignment"),
+ "_get_repo": ("_helpers", "_get_repo"),
+ "_is_path": ("_helpers", "_is_path"),
+ "create_mcp_server": ("_server", "create_mcp_server"),
+ "run_mcp": ("_server", "run_mcp"),
+}
+
+_surface_applied = False
+
+
+def ensure_full_surface() -> Any:
+ """Import every tool module and attach the registry to the FastMCP server.
+
+ This is the work that used to happen at package import. It is what makes
+ ``mcp`` a *populated* server rather than a bare instance, so every caller
+ that reads the advertised tool set has to go through here first:
+ ``create_mcp_server`` / ``run_mcp``, the ``mcp`` attribute itself, and the
+ selection layer (``apply_tool_selection`` / ``describe_tool_surface``,
+ which the dashboard's ``/mcp`` routes import directly).
+
+ Idempotent, and returns the server instance so callers need not re-import
+ it. Note that ``mcp_tool_registry.apply`` is itself a no-op on a repeat
+ call for the same server.
+ """
+ global _surface_applied
+ from repowise.server.mcp_server._server import mcp as _mcp
+
+ if _surface_applied:
+ return _mcp
+
+ for module in dict.fromkeys(_TOOL_MODULES.values()):
+ importlib.import_module(f"{__name__}.{module}")
+
+ from repowise.core.registry import mcp_tool_registry
+ from repowise.server.mcp_server._failure_shield import shield as _failure_shield
+ from repowise.server.mcp_server._savings import instrument as _savings_instrument
+ from repowise.server.mcp_server._tool_selection import snapshot_full_surface
+
+ # ``middleware`` wraps each tool twice, both layers signature-preserving so
+ # the tool schemas are unchanged. The failure shield sits innermost: no
+ # exception may escape to FastMCP as a protocol-level isError (an early
+ # isError teaches the agent to abandon the server for the whole session).
+ # The savings layer wraps it, so shaped error responses are still
+ # dead-end-debited in the ledger.
+ mcp_tool_registry.apply(
+ _mcp, middleware=lambda fn: _savings_instrument(_failure_shield(fn))
+ )
+
+ # Snapshot the full registered surface so per-server tool selection
+ # (single-repo vs workspace, config/CLI overrides) can rebuild from it.
+ # Selection itself runs later, once the repo path is known.
+ snapshot_full_surface(_mcp)
+
+ _surface_applied = True
+ return _mcp
+
# ---------------------------------------------------------------------------
# Backward-compatible access to _state globals.
@@ -110,9 +162,39 @@ _STATE_NAMES = frozenset(
def __getattr__(name: str) -> Any:
+ # State names proxy through to _state on every read — they are mutable and
+ # must never be cached onto this module.
if name in _STATE_NAMES:
return getattr(_state, name)
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+ if name == "mcp":
+ # Reading ``mcp`` means reading the advertised tool set, so the surface
+ # has to exist by the time it is handed over.
+ value: Any = ensure_full_surface()
+ elif name in _TOOL_MODULES:
+ value = getattr(
+ importlib.import_module(f"{__name__}.{_TOOL_MODULES[name]}"), name
+ )
+ elif name in _LAZY_ATTRS:
+ module_name, attr = _LAZY_ATTRS[name]
+ value = getattr(importlib.import_module(f"{__name__}.{module_name}"), attr)
+ else:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+ setattr(sys.modules[__name__], name, value)
+ return value
+
+
+def __dir__() -> list[str]:
+ """List the lazy names too, which ``__getattr__`` alone does not.
+
+ PEP 562 pairs the two for exactly this reason: without it a name resolves
+ fine through ``getattr`` but is invisible to ``dir()``, REPL completion, and
+ any ``name in dir(module)`` check.
+ """
+ return sorted(
+ set(globals()) | set(_STATE_NAMES) | set(_TOOL_MODULES) | set(_LAZY_ATTRS) | {"mcp"}
+ )
_Module = type(sys.modules[__name__])
@@ -135,6 +217,7 @@ __all__ = [
"_get_repo",
"_is_path",
"create_mcp_server",
+ "ensure_full_surface",
"generate_refactoring_code",
"get_answer",
"get_architecture",
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index dc638bda7..a55ab2f82 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -546,8 +546,13 @@ def create_mcp_server(
deltas, or ``"all"``); when omitted the ``mcp.tools`` config block is used.
"""
_state._repo_path = repo_path
+ from repowise.server.mcp_server import ensure_full_surface
from repowise.server.mcp_server._tool_selection import apply_tool_selection
+ # Tool modules import lazily now, so a server has to ask for the full
+ # surface before it can advertise (or trim) it.
+ ensure_full_surface()
+
apply_tool_selection(mcp, repo_path=repo_path, override=tools)
return mcp
@@ -565,8 +570,10 @@ def run_mcp(
when omitted, the ``mcp.tools`` config block is honoured.
"""
_state._repo_path = repo_path
+ from repowise.server.mcp_server import ensure_full_surface
from repowise.server.mcp_server._tool_selection import apply_tool_selection
+ ensure_full_surface()
apply_tool_selection(mcp, repo_path=repo_path, override=tools)
if transport == "sse":
diff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.py
index e89795974..afdea6f8f 100644
--- a/packages/server/src/repowise/server/mcp_server/_state.py
+++ b/packages/server/src/repowise/server/mcp_server/_state.py
@@ -3,10 +3,16 @@
from __future__ import annotations
import asyncio
-from typing import Any
+from typing import TYPE_CHECKING, Any
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+if TYPE_CHECKING:
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+# Deferred deliberately: this module is the one submodule the package imports
+# eagerly (every other module reads its globals), and pulling sqlalchemy in for
+# an annotation alone accounted for ~340ms of the ~345ms it used to cost. The
+# annotations are strings under `from __future__ import annotations` and are
+# never evaluated at runtime.
_session_factory: async_sessionmaker[AsyncSession] | None = None
_vector_store: Any = None
_decision_store: Any = None
diff --git a/packages/server/src/repowise/server/mcp_server/_tool_selection.py b/packages/server/src/repowise/server/mcp_server/_tool_selection.py
index 61a9a2997..5fbe52b43 100644
--- a/packages/server/src/repowise/server/mcp_server/_tool_selection.py
+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py
@@ -1,6 +1,7 @@
"""Selection of which MCP tools a server advertises.
-The registry attaches *every* tool to the FastMCP instance at import time. This
+The registry attaches *every* tool to the FastMCP instance the first time a
+caller asks for the full surface (``mcp_server.ensure_full_surface``). This
module trims that full set down to the surface a given server should expose,
based on three inputs:
@@ -57,12 +58,26 @@ _LEAN_WORKSPACE_EXTRAS = frozenset({"list_repos"})
_full_surface: dict[str, Any] | None = None
+def _ensure_registered() -> None:
+ """Make sure every tool module has been imported before reading the registry.
+
+ Tool modules import lazily (see ``mcp_server/__init__``), so the registry is
+ empty until something asks for the full surface. Both public entry points
+ here read ``mcp_tool_registry.entries()``, and both are imported directly by
+ callers that never touch the server instance — the dashboard's ``/mcp``
+ routes among them — so neither can assume registration already happened.
+ """
+ from repowise.server.mcp_server import ensure_full_surface
+
+ ensure_full_surface()
+
+
def snapshot_full_surface(mcp: Any) -> None:
"""Record the complete registered tool set so selection can rebuild from it.
- Called once at import, right after the registry attaches every tool. Safe to
- call again; the first non-empty snapshot wins so a later call (after the set
- has been trimmed) cannot shrink the source of truth.
+ Called once by ``ensure_full_surface``, right after the registry attaches
+ every tool. Safe to call again; the first non-empty snapshot wins so a later
+ call (after the set has been trimmed) cannot shrink the source of truth.
"""
global _full_surface
if _full_surface is not None:
@@ -196,6 +211,8 @@ def apply_tool_selection(
block when not given on the CLI), then removes every registered tool that is
not enabled. Returns the enabled set. Safe to call once per server boot.
"""
+ _ensure_registered()
+
if override is None:
override = _read_config_override(repo_path)
@@ -213,11 +230,19 @@ def apply_tool_selection(
# Rebuild from the full snapshot when available so selection is idempotent
# and can restore a tool a prior call trimmed; otherwise fall back to
# in-place removal of the currently-registered set.
+ #
+ # Sorted, because registration order is the order the tool modules were
+ # imported in, and that is no longer fixed: tool modules import lazily, so
+ # whichever consumer forces the surface first decides it (an HTTP app has
+ # already pulled tool_risk in through routers/git.py; a stdio server has
+ # not). The advertised order is what an agent reads top-down, so it should
+ # not depend on the entry point. Name order is arbitrary but stable, and it
+ # still puts get_answer first.
source = _full_surface if _full_surface is not None else dict(registered)
registered.clear()
- for name, tool in source.items():
+ for name in sorted(source):
if name in enabled:
- registered[name] = tool
+ registered[name] = source[name]
return enabled
@@ -238,6 +263,8 @@ def describe_tool_surface(repo_path: str | None) -> dict[str, Any]:
default set for this mode), ``requires_workspace``, and ``enabled`` (in the
currently-resolved surface).
"""
+ _ensure_registered()
+
entries = mcp_tool_registry.entries()
is_workspace = _is_workspace(repo_path)
override = _read_config_override(repo_path)
diff --git a/packages/server/src/repowise/server/routers/mcp.py b/packages/server/src/repowise/server/routers/mcp.py
index c79cde025..f03100c91 100644
--- a/packages/server/src/repowise/server/routers/mcp.py
+++ b/packages/server/src/repowise/server/routers/mcp.py
@@ -13,6 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
+from repowise.server import mcp_server as _mcp_server
from repowise.server.deps import resolve_request_session_factory, verify_api_key
from repowise.server.mcp_server._tool_selection import (
describe_tool_surface,
@@ -20,6 +21,14 @@ from repowise.server.mcp_server._tool_selection import (
)
from repowise.server.schemas import McpToolSurfaceResponse, UpdateMcpToolsRequest
+# Both endpoints below are ``async def`` and call ``describe_tool_surface``
+# synchronously, and that call imports all 17 tool modules the first time it
+# runs. Pay it here, at app import, so it lands before uvicorn starts serving
+# rather than inside the event loop on whichever request happens to be first —
+# which is where it used to land, back when importing ``_tool_selection`` pulled
+# the whole tool surface in as a side effect.
+_mcp_server.ensure_full_surface()
+
router = APIRouter(
prefix="/api/mcp",
tags=["mcp"],
diff --git a/tests/unit/server/mcp/test_mcp_docs_drift.py b/tests/unit/server/mcp/test_mcp_docs_drift.py
index 4dbdd2ef0..8b00c0c11 100644
--- a/tests/unit/server/mcp/test_mcp_docs_drift.py
+++ b/tests/unit/server/mcp/test_mcp_docs_drift.py
@@ -24,8 +24,11 @@ def doc_text() -> str:
def _entries():
- import repowise.server.mcp_server # noqa: F401 (registers the tools)
+ # Tool modules import lazily, so importing the package alone no longer
+ # registers anything — the surface has to be asked for explicitly.
+ from repowise.server.mcp_server import ensure_full_surface
+ ensure_full_surface()
return mcp_tool_registry.entries()
diff --git a/tests/unit/server/mcp/test_startup_budget.py b/tests/unit/server/mcp/test_startup_budget.py
new file mode 100644
index 000000000..9927c46c8
--- /dev/null
+++ b/tests/unit/server/mcp/test_startup_budget.py
@@ -0,0 +1,217 @@
+"""Import-cost budget for ``repowise.server.mcp_server``.
+
+The package used to import all 17 tool modules — and through them
+``core.analysis.health``, ``core.generation.onboarding``, FastMCP and
+sqlalchemy — at package import. Because a leaf import initialises its parent
+package first, importing any ONE tool cost ~2.5s against ~288ms for the entire
+CLI. That is the cost a CLI command adapting a single MCP tool would pay before
+doing any work, so the laziness is a load-bearing property, not an optimisation.
+
+These tests pin it structurally rather than by wall clock: the thing that
+regresses is an eager ``from repowise.server.mcp_server.tool_x import ...`` put
+back at the top of ``__init__.py``, and a module-presence assertion catches that
+exactly, on any machine, without timing flake. One loose wall-clock ratio guards
+the case where the weight arrives through a dependency nobody names here.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+from repowise.server import mcp_server
+from repowise.server.mcp_server import _TOOL_MODULES
+
+_PKG = "repowise.server.mcp_server"
+
+# Heavy third-party chains no consumer of a single tool should pay for at
+# package-import time. sqlalchemy is the one _state used to drag in for an
+# annotation alone; FastMCP arrives with _server, which only a running server
+# needs.
+_HEAVY_MODULES = ("sqlalchemy", "mcp.server.fastmcp", "lancedb")
+
+
+def _probe(body: str) -> dict:
+ """Run *body* in a clean interpreter and return the dict it prints as JSON.
+
+ A subprocess is the only honest measurement: pytest has already imported
+ most of this package by the time any test runs, so anything reading the
+ in-process ``sys.modules`` would pass no matter what ``__init__`` does.
+ """
+ proc = subprocess.run(
+ [sys.executable, "-c", textwrap.dedent(body)],
+ capture_output=True,
+ text=True,
+ timeout=180,
+ )
+ assert proc.returncode == 0, f"probe failed:\n{proc.stdout}\n{proc.stderr}"
+ return json.loads(proc.stdout.strip().splitlines()[-1])
+
+
+def test_bare_package_import_pulls_no_tool_module():
+ """Importing the package registers nothing and loads no tool module."""
+ seen = _probe(
+ f"""
+ import json, sys
+ import {_PKG}
+ from repowise.core.registry import mcp_tool_registry
+ print(json.dumps({{
+ "entries": len(mcp_tool_registry.entries()),
+ "tool_modules": [m for m in sys.modules if m.startswith("{_PKG}.tool_")],
+ "heavy": [m for m in {_HEAVY_MODULES!r} if m in sys.modules],
+ }}))
+ """
+ )
+ assert seen["entries"] == 0
+ assert seen["tool_modules"] == []
+ assert seen["heavy"] == []
+
+
+# Tools with no code-level relationship to get_answer. A genuine shared helper
+# may legitimately pull one tool module into another's chain (tool_answer reads
+# ``_prose_dominates`` out of tool_search, for instance), so the test names the
+# unrelated ones rather than demanding total isolation it should not enforce.
+_UNRELATED_TO_ANSWER = (
+ "tool_architecture",
+ "tool_conformance",
+ "tool_dead_code",
+ "tool_flows",
+ "tool_health",
+ "tool_refactoring",
+)
+
+
+def test_one_tool_does_not_drag_in_the_others():
+ """A single-tool consumer pays for that tool's chain, not the whole surface."""
+ seen = _probe(
+ f"""
+ import json, sys
+ from {_PKG} import get_answer
+ print(json.dumps({{
+ "loaded": sorted(
+ m for m in sys.modules
+ if m.startswith("{_PKG}.tool_") and m.count(".") == 3
+ ),
+ }}))
+ """
+ )
+ loaded = set(seen["loaded"])
+ assert f"{_PKG}.tool_answer" in loaded
+ unrelated = {f"{_PKG}.{name}" for name in _UNRELATED_TO_ANSWER}
+ assert loaded & unrelated == set()
+ # The eager version loaded all 17; today's chain is 3. The ceiling is set
+ # well clear of both so a new shared helper cross-import does not read as a
+ # laziness regression, while anything approaching the whole surface does.
+ assert len(loaded) <= 8, f"one tool import loaded {len(loaded)} tool modules: {sorted(loaded)}"
+
+
+def test_tool_modules_map_covers_every_tool_module_on_disk():
+ """``_TOOL_MODULES`` is hand-maintained; pin it to the package directory.
+
+ A new ``tool_*.py`` that registers a tool but is never added to the map is
+ silently never registered — ``ensure_full_surface`` iterates the map, not
+ the directory, so the tool exists and no server ever advertises it. Nothing
+ else catches that: ``test_tool_table_drift`` asserts table ⊆ registry, so
+ omitting the tool from both the map and the CLAUDE.md table passes.
+
+ Not a laziness test. It guards the duplicate that laziness introduced a
+ reason to care about (the old eager import block had the same trap).
+ """
+ pkg_dir = Path(mcp_server.__file__).parent
+ on_disk = {
+ p.stem if p.suffix == ".py" else p.name
+ for p in pkg_dir.iterdir()
+ if p.name.startswith("tool_") and (p.suffix == ".py" or (p / "__init__.py").is_file())
+ }
+ mapped = set(_TOOL_MODULES.values())
+ # Modules that hold shared helpers rather than a registered tool.
+ helpers_only = {"tool_search_symbols"}
+ unmapped = on_disk - mapped - helpers_only
+ assert not unmapped, (
+ f"tool modules missing from _TOOL_MODULES (they would never register): {sorted(unmapped)}"
+ )
+ assert mapped <= on_disk, f"_TOOL_MODULES names modules that do not exist: {mapped - on_disk}"
+
+
+def test_ensure_full_surface_registers_everything():
+ """The eager work still happens, just later — nothing was dropped.
+
+ An equivalence guard, not a laziness guard: it passes under an eager
+ ``__init__`` too. It is here because moving ``apply()`` out of the import
+ path is exactly the kind of change that drops a tool silently.
+ """
+ seen = _probe(
+ f"""
+ import json
+ import {_PKG} as m
+ m.ensure_full_surface()
+ from repowise.core.registry import mcp_tool_registry
+ print(json.dumps({{"entries": sorted(e.name for e in mcp_tool_registry.entries())}}))
+ """
+ )
+ assert set(seen["entries"]) == set(_TOOL_MODULES)
+
+
+def test_create_mcp_server_advertises_the_default_surface():
+ """``create_mcp_server`` forces the surface, so it still advertises tools.
+
+ Registration moved out of the import path; this is the assertion that the
+ move did not leave a server that boots with an empty tool list. Like the
+ test above it is an equivalence guard rather than a laziness guard, and it
+ additionally pins the advertised ORDER, which is no longer implied by the
+ import order of the tool modules.
+ """
+ seen = _probe(
+ f"""
+ import asyncio, json
+ import {_PKG} as m
+ srv = m.create_mcp_server(repo_path=None)
+ # NOT sorted here — the advertised order is part of what is asserted.
+ names = [t.name for t in asyncio.run(srv.list_tools())]
+ print(json.dumps({{"names": names}}))
+ """
+ )
+ # The curated single-repo default (see the package docstring).
+ assert "get_answer" in seen["names"]
+ assert "search_codebase" in seen["names"]
+ # Workspace-only and opt-in tools stay hidden, as before.
+ assert "get_blast_radius" not in seen["names"]
+ assert "get_dependency_path" not in seen["names"]
+ # Deterministic order regardless of which consumer forced the surface (an
+ # HTTP app has tool_risk imported by then, a stdio server has not).
+ assert seen["names"] == sorted(seen["names"])
+
+
+def _timed(args: list[str]) -> float:
+ start = time.perf_counter()
+ subprocess.run(args, capture_output=True, text=True, timeout=180, check=True)
+ return time.perf_counter() - start
+
+
+# Absolute, not a ratio. The package's own cost is a roughly fixed ~80ms that
+# does not shrink when the interpreter starts faster, so a multiple-of-baseline
+# budget is not scale-invariant: 2x on a Windows dev box (bare ~80ms) is 5x on
+# Linux CI (bare ~20ms) for identical work, and the test would fail there with
+# nothing wrong. The eager version cost ~2,700ms over baseline; this is ~80ms.
+_IMPORT_BUDGET_S = 0.6
+
+
+def test_package_import_stays_near_bare_interpreter_startup():
+ """Wall-clock backstop for weight arriving through an unnamed dependency.
+
+ The structural tests above catch an eager ``tool_*`` import by name. This
+ catches the case where the cost returns through something they do not name,
+ and is measured against this interpreter's own startup in the same run so a
+ slow or contended machine cancels out of the subtraction.
+ """
+ baseline = min(_timed([sys.executable, "-c", "pass"]) for _ in range(3))
+ package = min(_timed([sys.executable, "-c", f"import {_PKG}"]) for _ in range(3))
+ overhead = package - baseline
+ assert overhead < _IMPORT_BUDGET_S, (
+ f"importing {_PKG} costs {overhead:.3f}s over a bare interpreter "
+ f"(budget {_IMPORT_BUDGET_S}s) — something is being imported eagerly again"
+ )
diff --git a/tests/unit/server/mcp/test_tool_docstrings.py b/tests/unit/server/mcp/test_tool_docstrings.py
index 75032aecb..ce3b732ec 100644
--- a/tests/unit/server/mcp/test_tool_docstrings.py
+++ b/tests/unit/server/mcp/test_tool_docstrings.py
@@ -19,11 +19,13 @@ _MAX_FIRST_LINE_CHARS = 90
def _registered_tools():
- # Importing the package registers every @mcp.tool with the registry.
- import repowise.server.mcp_server # noqa: F401
+ # Tool modules import lazily, so asking for the full surface is what
+ # registers every @mcp.tool with the registry.
+ from repowise.server.mcp_server import ensure_full_surface
+ ensure_full_surface()
tools = mcp_tool_registry.tools()
- assert tools, "tool registry is empty — import side effect broken?"
+ assert tools, "tool registry is empty — ensure_full_surface broken?"
return tools
diff --git a/tests/unit/server/mcp/test_tool_selection.py b/tests/unit/server/mcp/test_tool_selection.py
index df887ea09..961bd8ed6 100644
--- a/tests/unit/server/mcp/test_tool_selection.py
+++ b/tests/unit/server/mcp/test_tool_selection.py
@@ -86,10 +86,11 @@ def test_lean_profile_workspace_adds_list_repos():
def test_lean_profile_full_registry():
"""Against the real registry, lean is exactly the agent-lean tools."""
- import repowise.server.mcp_server # noqa: F401 (registers the tools)
from repowise.core.registry import mcp_tool_registry
+ from repowise.server.mcp_server import ensure_full_surface
from repowise.server.mcp_server._tool_selection import LEAN_TOOLS
+ ensure_full_surface() # tool modules import lazily
enabled = resolve_enabled_tools(
mcp_tool_registry.entries(), is_workspace=False, override="lean"
)
@@ -108,9 +109,10 @@ def test_conformance_and_refactoring_are_opt_in():
Both must be named explicitly to appear; get_conformance stays workspace-gated
even when opted in.
"""
- import repowise.server.mcp_server # noqa: F401 (registers the tools)
from repowise.core.registry import mcp_tool_registry
+ from repowise.server.mcp_server import ensure_full_surface
+ ensure_full_surface() # tool modules import lazily
entries = mcp_tool_registry.entries()
single = resolve_enabled_tools(entries, is_workspace=False)
diff --git a/tests/unit/server/mcp/test_tool_table_drift.py b/tests/unit/server/mcp/test_tool_table_drift.py
index f600e8cc1..b7dabd207 100644
--- a/tests/unit/server/mcp/test_tool_table_drift.py
+++ b/tests/unit/server/mcp/test_tool_table_drift.py
@@ -15,8 +15,10 @@ from repowise.core.registry import mcp_tool_registry
def _registered_names() -> set[str]:
- import repowise.server.mcp_server # noqa: F401 (registers the tools)
+ # Tool modules import lazily; the surface has to be asked for.
+ from repowise.server.mcp_server import ensure_full_surface
+ ensure_full_surface()
return {fn.__name__ for fn in mcp_tool_registry.tools()}