Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): move tool selection into core and add an available_when predicate (#2846)
Raghav Chamadiya31b823b81888
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex d24103943..b26df3fbd 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -106,6 +106,8 @@ repowise mcp --all # every available toolWorkspace-only tools named explicitly in single-repo mode are ignored (they cannot do useful work there). Unknown tool names are ignored with a warning.+A tool registered with an `available_when` predicate over repository facts is hidden while that predicate is false, even when an override names it. Raw MCP clients get the list resolved when the server starts, while the in-product chat re-evaluates it on every turn.+**The `lean` profile** is the agent-lean surface: `get_answer`, `get_context`, `get_symbol`, `search_codebase`, `get_risk`, and `get_why`, plus `list_repos` in workspace mode (where repo aliases must be discoverable). `get_why` is part of the lean set because why/history questions are the category no code-search surface can answer from the tree alone; a lean profile without it measurably underperforms on exactly those questions. The profile advertises ~2.1k tokens of schema versus ~4.1k for the default surface. That is small enough to keep always loaded, so when a repo has `mcp.tools: lean` configured, `repowise init` skips the tool-search recommendation (the `ENABLE_TOOL_SEARCH` setting that defers MCP schemas behind a lookup round trip) for Claude Code; the six schemas the agent actually reaches for stay in context on every turn. init never turns an existing `ENABLE_TOOL_SEARCH` setting off, since it applies to every MCP server, not just repowise.**Or from the dashboard:** the Settings page lists every tool with its description and a per-repo toggle, and writes the same `mcp.tools` config for you.diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.pyindex 11b42f69e..617e3b178 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py@@ -101,7 +101,7 @@ def _uses_lean_tool_surface(repo_path: Path) -> bool:loaded, so init skips the tool-search (schema deferral) recommendation forit; deferral would reintroduce the schema-load round trip the profileexists to remove. Mirrors the "lean" token the selection layer resolves- (see ``repowise.server.mcp_server._tool_selection.LEAN``), read here via+ (see ``repowise.core.registry.tool_selection.LEAN``), read here viathe lightweight config loader so init does not import the server stack."""try:diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.pyindex 051d1ec28..635fbac90 100644--- a/packages/core/src/repowise/core/registry/mcp_tool_registry.py+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py@@ -33,7 +33,10 @@ from __future__ import annotationsfrom collections.abc import Callablefrom dataclasses import dataclass-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from .tool_selection import AvailabilityFactsTOOL_TIERS = frozenset({"canonical", "utility", "specialist"})TOOL_SAFETY_KINDS = frozenset({"read_only", "generative", "mutating"})@@ -57,6 +60,9 @@ class ToolEntry:marks whether the tool is part of the curated default surface; opt-in toolsset it ``False``. ``requires_workspace`` marks tools that only do usefulwork in workspace mode, so they are hidden from single-repo servers.+ ``available_when``, when set, is a predicate over+ :class:`~repowise.core.registry.tool_selection.AvailabilityFacts`; the tool+ is hidden whenever it returns ``False``."""fn: Callable[..., Any]@@ -71,6 +77,7 @@ class ToolEntry:presentation: str = "generic"safety: str = "read_only"evidence_basis: str = "unknown"+ available_when: Callable[[AvailabilityFacts], bool] | None = Noneclass MCPToolRegistry:@@ -80,6 +87,8 @@ class MCPToolRegistry:self._entries: list[ToolEntry] = []self._applied_to: list[Any] = []+ # The keyword list mirrors ToolEntry field by field and is due to collapse+ # into a single metadata object once another field joins it.def register(self,*args: Any,@@ -93,14 +102,15 @@ class MCPToolRegistry:presentation: str = "generic",safety: str = "read_only",evidence_basis: str = "unknown",+ available_when: Callable[[AvailabilityFacts], bool] | None = None,**kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]] | Callable[..., Any]:"""Decorator that schedules a function for FastMCP registration.Supports both decorator forms — bare ``@register`` and- ``@register()`` — so call sites read naturally. ``default`` and- ``requires_workspace`` annotate the tool for the selection layer- (see :class:`ToolEntry`); any other keyword arguments are reserved+ ``@register()`` — so call sites read naturally. ``default``,+ ``requires_workspace`` and ``available_when`` annotate the tool for+ the selection layer (see :class:`ToolEntry`); any other keyword arguments are reservedfor future ``description=`` / ``name=`` overrides and ignored."""@@ -143,6 +153,7 @@ class MCPToolRegistry:presentation=presentation,safety=safety,evidence_basis=evidence_basis,+ available_when=available_when,))fn.__dict__["__repowise_trust_kind__"] = trust_kinddiff --git a/packages/core/src/repowise/core/registry/tool_selection.py b/packages/core/src/repowise/core/registry/tool_selection.pynew file mode 100644index 000000000..67dc3df2d--- /dev/null+++ b/packages/core/src/repowise/core/registry/tool_selection.py@@ -0,0 +1,210 @@+"""Pure selection of which MCP tools a server exposes.++The surface is resolved from four inputs:++1. each tool's metadata (``default`` / ``requires_workspace`` /+ ``available_when`` on :class:`~repowise.core.registry.ToolEntry`),+2. whether the server is running in workspace mode,+3. an optional user override (a CLI ``--tools`` flag or a ``mcp.tools`` block in+ ``.repowise/config.yaml``), and+4. optional :class:`AvailabilityFacts` about the repository, which an entry's+ ``available_when`` predicate reads.++The default surface is every ``default`` tool that is usable in this mode. The+override can replace that set (an explicit allowlist, ``all``, ``lean``) or+adjust it (``+name`` / ``-name`` deltas). Nothing here does I/O: the server+gathers the inputs and applies the result to its FastMCP instance.+"""++from __future__ import annotations++import logging+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass, field++from .mcp_tool_registry import ToolEntry++_log = logging.getLogger("repowise.mcp")++# A value (CLI flag or config) of "all" enables every registered tool that is+# usable in the current mode, including opt-in and workspace-only tools.+ALL = "all"++# A value of "lean" enables the agent-lean profile: the pre-edit tools a+# coding agent actually reaches for, small enough that every schema can stay+# always-loaded instead of deferred behind a tool-search round trip. list_repos+# joins it in workspace mode only, where repo aliases must be discoverable.+# get_why belongs in the lean set: why/history questions are the category no+# graph- or search-shaped tool can answer, and a comparative benchmark run+# with a lean surface that omitted it scored repowise BELOW a bare agent on+# history-why questions — the differentiator was configured out, not absent.+LEAN = "lean"+LEAN_TOOLS = frozenset(+ {"get_answer", "get_context", "get_symbol", "search_codebase", "get_risk", "get_why"}+)+LEAN_WORKSPACE_EXTRAS = frozenset({"list_repos"})+++@dataclass(frozen=True)+class AvailabilityFacts:+ """Plain repository-level facts an ``available_when`` predicate can read.++ ``counts`` maps a fact name to a number (e.g. how many of something the+ index holds). A missing key reads as absent, so predicates should use+ ``facts.counts.get(name, 0)``. Kept deliberately small: add a field only+ when a registered predicate needs it and the server can compute it cheaply.+ """++ counts: Mapping[str, int] = field(default_factory=dict)+++def normalize_override(override: str | Sequence[str] | None) -> list[str] | None:+ """Coerce a raw override (CLI/config) into a clean list of tokens.++ Accepts ``None`` (no override), a comma- or whitespace-separated string, or+ a sequence of strings. Returns ``None`` when nothing meaningful was given so+ callers fall through to the default surface.+ """+ if override is None:+ return None+ if isinstance(override, str):+ tokens = [t.strip() for t in override.replace(",", " ").split()]+ else:+ tokens = [str(t).strip() for t in override]+ tokens = [t for t in tokens if t]+ return tokens or None+++def is_available(entry: ToolEntry, facts: AvailabilityFacts | None) -> bool:+ """Whether *entry*'s ``available_when`` predicate admits these facts.++ ``facts=None`` means the caller has no facts, so predicates are skipped and+ every entry counts as available. A predicate that raises hides its tool+ rather than taking the whole surface down with it.+ """+ if facts is None or entry.available_when is None:+ return True+ try:+ return bool(entry.available_when(facts))+ except Exception:+ _log.warning("MCP tool %r availability check failed; hiding it", entry.name, exc_info=True)+ return False+++def _usable_names(+ catalog: Mapping[str, ToolEntry], *, is_workspace: bool, facts: AvailabilityFacts | None+) -> set[str]:+ return {+ name+ for name, entry in catalog.items()+ if (is_workspace or not entry.requires_workspace) and is_available(entry, facts)+ }+++def _resolve_name(+ raw: str, catalog: Mapping[str, ToolEntry], usable: set[str], *, is_workspace: bool+) -> str | None:+ """Return *raw* when an override may enable it, logging why it may not."""+ entry = catalog.get(raw)+ if entry is None:+ _log.warning("Ignoring unknown MCP tool in selection: %r", raw)+ return None+ if raw in usable:+ return raw+ if entry.requires_workspace and not is_workspace:+ _log.warning("Ignoring workspace-only MCP tool %r outside workspace mode", raw)+ else:+ _log.warning("Ignoring MCP tool %r: not available for this repository", raw)+ return None+++def _is_keyword(tokens: list[str], keyword: str) -> bool:+ return len(tokens) == 1 and tokens[0].lower() == keyword+++def _is_delta(tokens: list[str]) -> bool:+ return all(t[0] in "+-" for t in tokens)+++def _lean_names(is_workspace: bool) -> frozenset[str]:+ return (LEAN_TOOLS | LEAN_WORKSPACE_EXTRAS) if is_workspace else LEAN_TOOLS+++def _apply_deltas(+ default_surface: set[str],+ tokens: list[str],+ catalog: Mapping[str, ToolEntry],+ usable: set[str],+ *,+ is_workspace: bool,+) -> set[str]:+ """Apply ``+name`` / ``-name`` tokens, in order, to the default surface."""+ enabled = set(default_surface)+ for token in tokens:+ op, raw = token[0], token[1:].strip()+ if op == "-":+ enabled.discard(raw)+ elif _resolve_name(raw, catalog, usable, is_workspace=is_workspace):+ enabled.add(raw)+ return enabled+++def _allowlist(+ tokens: list[str],+ catalog: Mapping[str, ToolEntry],+ usable: set[str],+ *,+ is_workspace: bool,+) -> set[str]:+ """Only the named tools, minus any an override may not enable."""+ return {t for t in tokens if _resolve_name(t, catalog, usable, is_workspace=is_workspace)}+++def resolve_enabled_tools(+ entries: Iterable[ToolEntry],+ *,+ is_workspace: bool,+ override: str | Sequence[str] | None = None,+ facts: AvailabilityFacts | None = None,+) -> set[str]:+ """Return the set of tool names a server should expose.++ ``override`` semantics:++ - ``None`` / empty: the curated default surface.+ - ``"all"`` (or ``["all"]``): every tool usable in the current mode.+ - ``"lean"``: the agent-lean profile (see :data:`LEAN_TOOLS`).+ - all tokens prefixed ``+``/``-``: deltas applied to the default surface.+ - otherwise: an explicit allowlist (only the named tools).++ A tool is usable when its mode fits (workspace-only tools need a workspace)+ and its ``available_when`` predicate, if any, holds for *facts*. No+ override can enable an unusable tool, even by name: it could not do useful+ work here. ``facts=None`` skips predicates.+ """+ catalog = {e.name: e for e in entries}+ usable = _usable_names(catalog, is_workspace=is_workspace, facts=facts)+ default_surface = {name for name in usable if catalog[name].default}++ tokens = normalize_override(override)+ if tokens is None:+ return default_surface+ if _is_keyword(tokens, ALL):+ return usable+ if _is_keyword(tokens, LEAN):+ return usable & _lean_names(is_workspace)+ if _is_delta(tokens):+ return _apply_deltas(default_surface, tokens, catalog, usable, is_workspace=is_workspace)+ return _allowlist(tokens, catalog, usable, is_workspace=is_workspace)+++__all__ = [+ "ALL",+ "LEAN",+ "LEAN_TOOLS",+ "LEAN_WORKSPACE_EXTRAS",+ "AvailabilityFacts",+ "is_available",+ "normalize_override",+ "resolve_enabled_tools",+]diff --git a/packages/server/src/repowise/server/mcp_server/_tool_selection.py b/packages/server/src/repowise/server/mcp_server/_tool_selection.pyindex a253788ac..33430faa2 100644--- a/packages/server/src/repowise/server/mcp_server/_tool_selection.py+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py@@ -1,24 +1,17 @@-"""Selection of which MCP tools a server advertises.+"""Server side of MCP tool selection: gather inputs, apply the result.++The pure rules live in :mod:`repowise.core.registry.tool_selection`. This+module reads their inputs from disk (the ``mcp.tools`` config override,+workspace mode, :class:`AvailabilityFacts`) and applies the resolved set to+the FastMCP instance.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:--1. each tool's metadata (``default`` / ``requires_workspace`` from- :class:`~repowise.core.registry.ToolEntry`),-2. whether the server is running in workspace mode, and-3. an optional user override (a CLI ``--tools`` flag or a ``mcp.tools`` block in- ``.repowise/config.yaml``).--The default surface is the curated set: every ``default`` tool, minus the-workspace-only ones when not in a workspace. The override can either replace-that set entirely (an explicit allowlist) or adjust it (``+name`` / ``-name``-deltas), so "expose the default plus one more" stays a one-line config edit.--Filtering happens once, after registration, by removing the deselected tools-from the FastMCP tool manager. There is no per-call cost and tool schemas are-untouched.+caller asks for the full surface (``mcp_server.ensure_full_surface``).+:func:`apply_tool_selection` then trims that set once, at boot, by removing the+deselected tools from the FastMCP tool manager, so raw MCP clients see the+surface as it stood when the server started. Chat calls+:func:`selected_tool_entries` instead, which re-resolves on every turn. There+is no per-call cost and tool schemas are untouched."""from __future__ import annotations@@ -30,27 +23,10 @@ from pathlib import Pathfrom typing import Anyfrom repowise.core.registry import ToolEntry, mcp_tool_registry+from repowise.core.registry.tool_selection import ALL, AvailabilityFacts, resolve_enabled_tools_log = logging.getLogger("repowise.mcp")-# A value (CLI flag or config) of "all" enables every registered tool that is-# usable in the current mode, including opt-in and workspace-only tools.-ALL = "all"--# A value of "lean" enables the agent-lean profile: the pre-edit tools a-# coding agent actually reaches for, small enough that every schema can stay-# always-loaded instead of deferred behind a tool-search round trip. list_repos-# joins it in workspace mode only, where repo aliases must be discoverable.-# get_why belongs in the lean set: why/history questions are the category no-# graph- or search-shaped tool can answer, and a comparative benchmark run-# with a lean surface that omitted it scored repowise BELOW a bare agent on-# history-why questions — the differentiator was configured out, not absent.-LEAN = "lean"-LEAN_TOOLS = frozenset(- {"get_answer", "get_context", "get_symbol", "search_codebase", "get_risk", "get_why"}-)-_LEAN_WORKSPACE_EXTRAS = frozenset({"list_repos"})-# Snapshot of every tool registered on the server, captured once after the# registry applies them and before any selection trims the live set. Selection# rebuilds the advertised set from this snapshot, so it is idempotent and can@@ -90,87 +66,6 @@ def snapshot_full_surface(mcp: Any) -> None:_full_surface = dict(registered)-def _normalize_override(override: str | Sequence[str] | None) -> list[str] | None:- """Coerce a raw override (CLI/config) into a clean list of tokens.-- Accepts ``None`` (no override), a comma- or whitespace-separated string, or- a sequence of strings. Returns ``None`` when nothing meaningful was given so- callers fall through to the default surface.- """- if override is None:- return None- if isinstance(override, str):- tokens = [t.strip() for t in override.replace(",", " ").split()]- else:- tokens = [str(t).strip() for t in override]- tokens = [t for t in tokens if t]- return tokens or None---def resolve_enabled_tools(- entries: Iterable[ToolEntry],- *,- is_workspace: bool,- override: str | Sequence[str] | None = None,-) -> set[str]:- """Return the set of tool names a server should expose.-- ``override`` semantics:-- - ``None`` / empty: the curated default surface.- - ``"all"`` (or ``["all"]``): every tool usable in the current mode.- - ``"lean"``: the agent-lean profile (see :data:`LEAN_TOOLS`).- - all tokens prefixed ``+``/``-``: deltas applied to the default surface.- - otherwise: an explicit allowlist (only the named tools).-- Workspace-only tools are never enabled outside a workspace, even when named- explicitly, because they cannot do useful work there.- """- catalog = {e.name: e for e in entries}-- def usable(entry: ToolEntry) -> bool:- return is_workspace or not entry.requires_workspace-- default_surface = {name for name, e in catalog.items() if e.default and usable(e)}-- tokens = _normalize_override(override)- if tokens is None:- return default_surface-- if len(tokens) == 1 and tokens[0].lower() == ALL:- return {name for name, e in catalog.items() if usable(e)}-- if len(tokens) == 1 and tokens[0].lower() == LEAN:- names = LEAN_TOOLS | (_LEAN_WORKSPACE_EXTRAS if is_workspace else frozenset())- return {n for n in names if n in catalog and usable(catalog[n])}-- def resolve_name(raw: str) -> str | None:- entry = catalog.get(raw)- if entry is None:- _log.warning("Ignoring unknown MCP tool in selection: %r", raw)- return None- if not usable(entry):- _log.warning("Ignoring workspace-only MCP tool %r outside workspace mode", raw)- return None- return raw-- is_delta = all(t[0] in "+-" for t in tokens)- if is_delta:- enabled = set(default_surface)- for token in tokens:- op, raw = token[0], token[1:].strip()- if op == "-":- enabled.discard(raw)- continue- name = resolve_name(raw)- if name is not None:- enabled.add(name)- return enabled-- # Explicit allowlist.- return {name for name in (resolve_name(t) for t in tokens) if name is not None}--def _read_config_override(repo_path: str | None) -> str | Sequence[str] | None:"""Read ``mcp.tools`` from ``.repowise/config.yaml`` if present."""if not repo_path:@@ -198,6 +93,17 @@ def _is_workspace(repo_path: str | None) -> bool:return False+def _availability_facts(repo_path: str | None) -> AvailabilityFacts:+ """Facts that ``available_when`` predicates read for *repo_path*.++ Chat calls this every turn, so it must stay cheap: no database queries.+ No registered tool gates on a fact yet, so there is nothing to compute;+ when one does, add its fact here from a cheap source (config, a file on+ disk) and extend :class:`AvailabilityFacts` to carry it.+ """+ return AvailabilityFacts()++def apply_tool_selection(mcp: Any,*,@@ -221,6 +127,7 @@ def apply_tool_selection(mcp_tool_registry.entries(),is_workspace=is_workspace,override=override,+ facts=_availability_facts(repo_path),)global _selected_surface_selected_surface = (is_workspace, frozenset(enabled))@@ -263,7 +170,8 @@ def selected_tool_entries(repo_path: str | None) -> list[ToolEntry]:This is the shared selection seam for external MCP clients and in-productchat. It deliberately resolves from the live registry on every request so- neither surface can grow a second catalog or retain a stale config view.+ neither surface can grow a second catalog or retain a stale config view,+ and so ``available_when`` predicates are re-evaluated every chat turn."""_ensure_registered()entries = mcp_tool_registry.entries()@@ -271,6 +179,7 @@ def selected_tool_entries(repo_path: str | None) -> list[ToolEntry]:entries,is_workspace=_is_workspace(repo_path),override=_read_config_override(repo_path),+ facts=_availability_facts(repo_path),)return [entry@@ -333,24 +242,32 @@ def describe_tool_surface(repo_path: str | None) -> dict[str, Any]:Returns ``is_workspace``, the raw ``override`` currently in config, and onerow per registered tool with its name, one-line description, and the flags aUI needs to render and edit the selection: ``default`` (in the curated- default set for this mode), ``requires_workspace``, and ``enabled`` (in the- currently-resolved surface).+ default set for this mode), ``requires_workspace``, ``eligible`` (usable in+ this mode for this repo), 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)+ facts = _availability_facts(repo_path)++ def resolve(value: str | Sequence[str] | None) -> set[str]:+ return resolve_enabled_tools(+ entries, is_workspace=is_workspace, override=value, facts=facts+ )- default_surface = resolve_enabled_tools(entries, is_workspace=is_workspace, override=None)- enabled = resolve_enabled_tools(entries, is_workspace=is_workspace, override=override)+ default_surface = resolve(None)+ enabled = resolve(override)+ # "all" is exactly the usable set: right mode and predicate satisfied.+ eligible = resolve(ALL)rows = registry_tool_rows(entries)tools = [{**row,"default": row["name"] in default_surface,- "eligible": row["eligible_workspace"] if is_workspace else row["eligible_single_repo"],+ "eligible": row["name"] in eligible,"enabled": row["name"] in enabled,}for row in rowsdiff --git a/scripts/gen_agent_matrix.py b/scripts/gen_agent_matrix.pyindex 3c534d248..7c27cfad1 100644--- a/scripts/gen_agent_matrix.py+++ b/scripts/gen_agent_matrix.py@@ -136,8 +136,8 @@ def tool_counts() -> dict[str, int]:be imported already."""from repowise.core.registry import mcp_tool_registry+ from repowise.core.registry.tool_selection import LEAN, resolve_enabled_toolsfrom repowise.server.mcp_server import ensure_full_surface- from repowise.server.mcp_server._tool_selection import LEAN, resolve_enabled_toolsensure_full_surface()entries = mcp_tool_registry.entries()diff --git a/tests/unit/cli/test_agent_matrix.py b/tests/unit/cli/test_agent_matrix.pyindex 580b623db..e440a866a 100644--- a/tests/unit/cli/test_agent_matrix.py+++ b/tests/unit/cli/test_agent_matrix.py@@ -295,8 +295,8 @@ COUNT_CLAIMS: tuple[tuple[str, str, str], ...] = (def test_the_flagship_set_is_a_real_subset_of_the_default_surface() -> None:"""The published flagship count is exactly the registry canonical tier."""from repowise.core.registry import mcp_tool_registry+ from repowise.core.registry.tool_selection import resolve_enabled_toolsfrom repowise.server.mcp_server import ensure_full_surface- from repowise.server.mcp_server._tool_selection import resolve_enabled_toolsensure_full_surface()entries = mcp_tool_registry.entries()diff --git a/tests/unit/registry/test_mcp_tool_registry.py b/tests/unit/registry/test_mcp_tool_registry.pyindex 8d1c00902..9c508cd2b 100644--- a/tests/unit/registry/test_mcp_tool_registry.py+++ b/tests/unit/registry/test_mcp_tool_registry.py@@ -109,3 +109,20 @@ def test_reset_clears_tools(registry):registry.reset()assert registry.tools() == []+++def test_register_stores_available_when_as_is(registry):+ def needs_flows(facts) -> bool:+ return facts.counts.get("flows", 0) > 0++ @registry.register(available_when=needs_flows)+ async def gated() -> dict:+ return {}++ @registry.register+ async def plain() -> dict:+ return {}++ by_name = {entry.name: entry for entry in registry.entries()}+ assert by_name["gated"].available_when is needs_flows+ assert by_name["plain"].available_when is Nonediff --git a/tests/unit/registry/test_mcp_tool_selection.py b/tests/unit/registry/test_mcp_tool_selection.pynew file mode 100644index 000000000..b8d002593--- /dev/null+++ b/tests/unit/registry/test_mcp_tool_selection.py@@ -0,0 +1,231 @@+"""Pure MCP tool-surface selection rules (repowise.core.registry.tool_selection)."""++from __future__ import annotations++import logging++from repowise.core.registry import ToolEntry+from repowise.core.registry.tool_selection import (+ AvailabilityFacts,+ is_available,+ normalize_override,+ resolve_enabled_tools,+)+++def _fn(name):+ def f(): # pragma: no cover - never called+ return None++ f.__name__ = name+ return f+++# A representative catalog: canonical defaults, one workspace utility, and specialists.+CATALOG = [+ ToolEntry(_fn("get_answer"), "get_answer"),+ ToolEntry(_fn("get_context"), "get_context"),+ ToolEntry(+ _fn("list_repos"),+ "list_repos",+ requires_workspace=True,+ tier="utility",+ ),+ ToolEntry(+ _fn("get_blast_radius"),+ "get_blast_radius",+ default=False,+ requires_workspace=True,+ tier="specialist",+ ),+ ToolEntry(_fn("get_dependency_path"), "get_dependency_path", default=False),+]+++def test_default_single_repo_surface():+ enabled = resolve_enabled_tools(CATALOG, is_workspace=False)+ assert enabled == {"get_answer", "get_context"}+++def test_default_workspace_adds_workspace_only():+ enabled = resolve_enabled_tools(CATALOG, is_workspace=True)+ assert enabled == {"get_answer", "get_context", "list_repos"}+++def test_opt_in_tool_off_by_default():+ assert "get_dependency_path" not in resolve_enabled_tools(CATALOG, is_workspace=True)+++def test_delta_add_and_remove():+ enabled = resolve_enabled_tools(+ CATALOG, is_workspace=False, override="+get_dependency_path,-get_context"+ )+ assert enabled == {"get_answer", "get_dependency_path"}+++def test_delta_string_or_list_equivalent():+ a = resolve_enabled_tools(CATALOG, is_workspace=False, override="+get_dependency_path")+ b = resolve_enabled_tools(CATALOG, is_workspace=False, override=["+get_dependency_path"])+ assert a == b == {"get_answer", "get_context", "get_dependency_path"}+++def test_explicit_allowlist_replaces_default():+ enabled = resolve_enabled_tools(+ CATALOG, is_workspace=False, override="get_answer,get_dependency_path"+ )+ assert enabled == {"get_answer", "get_dependency_path"}+++def test_all_enables_everything_usable():+ assert resolve_enabled_tools(CATALOG, is_workspace=True, override="all") == {+ e.name for e in CATALOG+ }+ # In single-repo, "all" still excludes workspace-only tools.+ assert resolve_enabled_tools(CATALOG, is_workspace=False, override="all") == {+ "get_answer",+ "get_context",+ "get_dependency_path",+ }+++def test_lean_profile_single_repo():+ # Intersected with the catalog: only the lean tools this registry has.+ enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="lean")+ assert enabled == {"get_answer", "get_context"}+++def test_lean_profile_workspace_adds_list_repos():+ enabled = resolve_enabled_tools(CATALOG, is_workspace=True, override="LEAN")+ assert enabled == {"get_answer", "get_context", "list_repos"}+++def test_workspace_only_named_explicitly_is_dropped_single_repo():+ enabled = resolve_enabled_tools(+ CATALOG, is_workspace=False, override="get_answer,get_blast_radius"+ )+ assert enabled == {"get_answer"}+++def test_workspace_only_named_explicitly_kept_in_workspace():+ enabled = resolve_enabled_tools(+ CATALOG, is_workspace=True, override="get_answer,get_blast_radius"+ )+ assert enabled == {"get_answer", "get_blast_radius"}+++def test_unknown_tool_ignored():+ enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="+does_not_exist")+ assert enabled == {"get_answer", "get_context"}+++def test_empty_override_falls_back_to_default():+ assert resolve_enabled_tools(CATALOG, is_workspace=False, override="") == (+ resolve_enabled_tools(CATALOG, is_workspace=False)+ )+++def test_normalize_override_shapes():+ assert normalize_override(None) is None+ assert normalize_override(" , ") is None+ assert normalize_override("a, b c") == ["a", "b", "c"]+ assert normalize_override([" a ", ""]) == ["a"]+++# --- available_when --------------------------------------------------------++HAS_FLOWS = AvailabilityFacts(counts={"flows": 2})+NO_FLOWS = AvailabilityFacts()+++def _needs_flows(facts: AvailabilityFacts) -> bool:+ return facts.counts.get("flows", 0) > 0+++GATED = [+ *CATALOG,+ ToolEntry(_fn("get_flow_map"), "get_flow_map", available_when=_needs_flows),+ ToolEntry(+ _fn("get_flow_extra"),+ "get_flow_extra",+ default=False,+ tier="specialist",+ available_when=_needs_flows,+ ),+ ToolEntry(+ _fn("get_ws_flows"),+ "get_ws_flows",+ default=False,+ requires_workspace=True,+ tier="specialist",+ available_when=_needs_flows,+ ),+]+++def test_predicate_true_keeps_the_default_tool():+ assert "get_flow_map" in resolve_enabled_tools(GATED, is_workspace=False, facts=HAS_FLOWS)+++def test_predicate_false_hides_the_default_tool():+ enabled = resolve_enabled_tools(GATED, is_workspace=False, facts=NO_FLOWS)+ assert enabled == {"get_answer", "get_context"}+++def test_no_facts_skips_predicates():+ assert "get_flow_map" in resolve_enabled_tools(GATED, is_workspace=False)+++def test_override_naming_a_gated_tool_still_hides_it(caplog):+ with caplog.at_level(logging.WARNING, logger="repowise.mcp"):+ delta = resolve_enabled_tools(+ GATED, is_workspace=False, override="+get_flow_extra", facts=NO_FLOWS+ )+ allow = resolve_enabled_tools(+ GATED, is_workspace=False, override="get_answer,get_flow_map", facts=NO_FLOWS+ )+ assert "get_flow_extra" not in delta+ assert allow == {"get_answer"}+ assert "not available for this repository" in caplog.text+++def test_override_naming_a_gated_tool_enables_it_when_available():+ enabled = resolve_enabled_tools(+ GATED, is_workspace=False, override="+get_flow_extra", facts=HAS_FLOWS+ )+ assert "get_flow_extra" in enabled+++def test_all_and_lean_respect_predicates():+ assert "get_flow_extra" not in resolve_enabled_tools(+ GATED, is_workspace=False, override="all", facts=NO_FLOWS+ )+ assert "get_flow_extra" in resolve_enabled_tools(+ GATED, is_workspace=False, override="all", facts=HAS_FLOWS+ )+++def test_workspace_gate_and_predicate_both_apply(caplog):+ # A satisfied predicate does not lift the workspace requirement...+ with caplog.at_level(logging.WARNING, logger="repowise.mcp"):+ single = resolve_enabled_tools(+ GATED, is_workspace=False, override="+get_ws_flows", facts=HAS_FLOWS+ )+ assert "get_ws_flows" not in single+ assert "outside workspace mode" in caplog.text+ # ...and a workspace does not lift a failing predicate.+ assert "get_ws_flows" not in resolve_enabled_tools(+ GATED, is_workspace=True, override="+get_ws_flows", facts=NO_FLOWS+ )+ assert "get_ws_flows" in resolve_enabled_tools(+ GATED, is_workspace=True, override="+get_ws_flows", facts=HAS_FLOWS+ )+++def test_a_raising_predicate_hides_only_its_tool():+ def boom(_facts):+ raise RuntimeError("bad plugin")++ entry = ToolEntry(_fn("get_boom"), "get_boom", available_when=boom)+ assert is_available(entry, NO_FLOWS) is False+ enabled = resolve_enabled_tools([*CATALOG, entry], is_workspace=False, facts=NO_FLOWS)+ assert enabled == {"get_answer", "get_context"}diff --git a/tests/unit/server/mcp/test_mcp_docs_drift.py b/tests/unit/server/mcp/test_mcp_docs_drift.pyindex 2ac323467..b21f7bbef 100644--- a/tests/unit/server/mcp/test_mcp_docs_drift.py+++ b/tests/unit/server/mcp/test_mcp_docs_drift.py@@ -13,7 +13,7 @@ from pathlib import Pathimport pytestfrom repowise.core.registry import mcp_tool_registry-from repowise.server.mcp_server._tool_selection import LEAN_TOOLS+from repowise.core.registry.tool_selection import LEAN_TOOLSDOC = Path(__file__).parents[4] / "docs" / "agent" / "MCP_TOOLS.md"diff --git a/tests/unit/server/mcp/test_overview_surface.py b/tests/unit/server/mcp/test_overview_surface.pyindex 421fb2450..d9467598b 100644--- a/tests/unit/server/mcp/test_overview_surface.py+++ b/tests/unit/server/mcp/test_overview_surface.py@@ -9,10 +9,8 @@ import jsonimport pytestfrom repowise.core.registry import ToolEntry, ToolRecipe-from repowise.server.mcp_server._tool_selection import (- registry_tool_rows,- resolve_enabled_tools,-)+from repowise.core.registry.tool_selection import resolve_enabled_tools+from repowise.server.mcp_server._tool_selection import registry_tool_rowsfrom repowise.server.mcp_server.tool_overview import _tool_surface_guidediff --git a/tests/unit/server/mcp/test_symbol_not_advertised.py b/tests/unit/server/mcp/test_symbol_not_advertised.pyindex ed5ac8a92..f696ad61a 100644--- a/tests/unit/server/mcp/test_symbol_not_advertised.py+++ b/tests/unit/server/mcp/test_symbol_not_advertised.py@@ -22,7 +22,7 @@ from __future__ import annotationsfrom repowise.cli.commands.augment_cmd.session_start import _CORE_TOOLSfrom repowise.core.generation.editor_files.tool_table import TOOL_TABLE_ROWS-from repowise.server.mcp_server._tool_selection import LEAN_TOOLS+from repowise.core.registry.tool_selection import LEAN_TOOLSdef test_get_symbol_is_still_served():diff --git a/tests/unit/server/mcp/test_tool_selection.py b/tests/unit/server/mcp/test_tool_selection.pyindex 3f2da4c70..41a280e86 100644--- a/tests/unit/server/mcp/test_tool_selection.py+++ b/tests/unit/server/mcp/test_tool_selection.py@@ -1,104 +1,20 @@-"""Tests for the configurable MCP tool surface (_tool_selection)."""+"""MCP tool surface against the real registry and the live FastMCP server.++The pure selection rules are tested in tests/unit/registry/test_mcp_tool_selection.py.+"""from __future__ import annotationsimport pytest-from repowise.core.registry import ToolEntry-from repowise.server.mcp_server._tool_selection import resolve_enabled_tools---def _fn(name):- def f(): # pragma: no cover - never called- return None-- f.__name__ = name- return f---# A representative catalog: canonical defaults, one workspace utility, and specialists.-CATALOG = [- ToolEntry(_fn("get_answer"), "get_answer"),- ToolEntry(_fn("get_context"), "get_context"),- ToolEntry(- _fn("list_repos"),- "list_repos",- requires_workspace=True,- tier="utility",- ),- ToolEntry(- _fn("get_blast_radius"),- "get_blast_radius",- default=False,- requires_workspace=True,- tier="specialist",- ),- ToolEntry(_fn("get_dependency_path"), "get_dependency_path", default=False),-]---def test_default_single_repo_surface():- enabled = resolve_enabled_tools(CATALOG, is_workspace=False)- assert enabled == {"get_answer", "get_context"}---def test_default_workspace_adds_workspace_only():- enabled = resolve_enabled_tools(CATALOG, is_workspace=True)- assert enabled == {"get_answer", "get_context", "list_repos"}---def test_opt_in_tool_off_by_default():- assert "get_dependency_path" not in resolve_enabled_tools(CATALOG, is_workspace=True)---def test_delta_add_and_remove():- enabled = resolve_enabled_tools(- CATALOG, is_workspace=False, override="+get_dependency_path,-get_context"- )- assert enabled == {"get_answer", "get_dependency_path"}---def test_delta_string_or_list_equivalent():- a = resolve_enabled_tools(CATALOG, is_workspace=False, override="+get_dependency_path")- b = resolve_enabled_tools(CATALOG, is_workspace=False, override=["+get_dependency_path"])- assert a == b == {"get_answer", "get_context", "get_dependency_path"}---def test_explicit_allowlist_replaces_default():- enabled = resolve_enabled_tools(- CATALOG, is_workspace=False, override="get_answer,get_dependency_path"- )- assert enabled == {"get_answer", "get_dependency_path"}---def test_all_enables_everything_usable():- assert resolve_enabled_tools(CATALOG, is_workspace=True, override="all") == {- e.name for e in CATALOG- }- # In single-repo, "all" still excludes workspace-only tools.- assert resolve_enabled_tools(CATALOG, is_workspace=False, override="all") == {- "get_answer",- "get_context",- "get_dependency_path",- }---def test_lean_profile_single_repo():- # Intersected with the catalog: only the lean tools this registry has.- enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="lean")- assert enabled == {"get_answer", "get_context"}---def test_lean_profile_workspace_adds_list_repos():- enabled = resolve_enabled_tools(CATALOG, is_workspace=True, override="LEAN")- assert enabled == {"get_answer", "get_context", "list_repos"}+from repowise.core.registry.tool_selection import resolve_enabled_toolsdef test_lean_profile_full_registry():"""Against the real registry, lean is exactly the agent-lean tools."""from repowise.core.registry import mcp_tool_registry+ from repowise.core.registry.tool_selection import LEAN_TOOLSfrom repowise.server.mcp_server import ensure_full_surface- from repowise.server.mcp_server._tool_selection import LEAN_TOOLSensure_full_surface() # tool modules import lazilyenabled = resolve_enabled_tools(@@ -145,31 +61,6 @@ def test_conformance_and_refactoring_are_opt_in():assert "get_conformance" not in opted_single-def test_workspace_only_named_explicitly_is_dropped_single_repo():- enabled = resolve_enabled_tools(- CATALOG, is_workspace=False, override="get_answer,get_blast_radius"- )- assert enabled == {"get_answer"}---def test_workspace_only_named_explicitly_kept_in_workspace():- enabled = resolve_enabled_tools(- CATALOG, is_workspace=True, override="get_answer,get_blast_radius"- )- assert enabled == {"get_answer", "get_blast_radius"}---def test_unknown_tool_ignored():- enabled = resolve_enabled_tools(CATALOG, is_workspace=False, override="+does_not_exist")- assert enabled == {"get_answer", "get_context"}---def test_empty_override_falls_back_to_default():- assert resolve_enabled_tools(CATALOG, is_workspace=False, override="") == (- resolve_enabled_tools(CATALOG, is_workspace=False)- )--def test_real_registry_phase_one_surfaces_are_exact():from repowise.core.registry import mcp_tool_registryfrom repowise.server.mcp_server import ensure_full_surface@@ -254,3 +145,49 @@ async def test_apply_trims_and_restores_live_server(tmp_path, monkeypatch):if _tool_selection._full_surface is not None:mcp._tool_manager._tools = dict(_tool_selection._full_surface)_tool_selection._selected_surface = None+++# --- available_when, boot and settings ------------------------------------+++def _gate(monkeypatch, name: str) -> None:+ """Gate one live entry on a ``flows`` fact the default facts do not carry."""+ from dataclasses import replace++ from repowise.core.registry import mcp_tool_registry+ from repowise.server.mcp_server import ensure_full_surface++ ensure_full_surface()+ gated = [+ replace(e, available_when=lambda f: f.counts.get("flows", 0) > 0) if e.name == name else e+ for e in mcp_tool_registry.entries()+ ]+ monkeypatch.setattr(mcp_tool_registry, "entries", lambda: list(gated))+++def test_boot_selection_evaluates_predicates(tmp_path, monkeypatch):+ from repowise.server.mcp_server import _tool_selection++ _gate(monkeypatch, "get_health")+ monkeypatch.setattr(_tool_selection, "_is_workspace", lambda _path: False)+ monkeypatch.setattr(_tool_selection, "_selected_surface", None)++ enabled = _tool_selection.apply_tool_selection(object(), repo_path=str(tmp_path))++ assert "get_health" not in enabled+ assert "get_answer" in enabled+++def test_settings_surface_marks_a_gated_tool_ineligible(tmp_path, monkeypatch):+ from repowise.server.mcp_server import _tool_selection++ _gate(monkeypatch, "get_health")+ monkeypatch.setattr(_tool_selection, "_is_workspace", lambda _path: False)++ rows = {+ row["name"]: row for row in _tool_selection.describe_tool_surface(str(tmp_path))["tools"]+ }++ assert rows["get_health"]["eligible"] is False+ assert rows["get_health"]["enabled"] is False+ assert rows["get_answer"]["eligible"] is Truediff --git a/tests/unit/server/test_chat_tool_registry.py b/tests/unit/server/test_chat_tool_registry.pyindex a2effe3bc..94cc52225 100644--- a/tests/unit/server/test_chat_tool_registry.py+++ b/tests/unit/server/test_chat_tool_registry.py@@ -2,19 +2,21 @@from __future__ import annotations+from dataclasses import replacefrom unittest.mock import patchimport pytest-from repowise.core.registry import ToolEntry+from repowise.core.registry import ToolEntry, mcp_tool_registry+from repowise.core.registry.tool_selection import AvailabilityFacts, resolve_enabled_toolsfrom repowise.server import chat_toolsfrom repowise.server.mcp_server import _tool_selection, ensure_full_surfacedef test_chat_catalog_matches_the_selected_mcp_surface(tmp_path) -> None:ensure_full_surface()- selected = _tool_selection.resolve_enabled_tools(- _tool_selection.mcp_tool_registry.entries(),+ selected = resolve_enabled_tools(+ mcp_tool_registry.entries(),is_workspace=_tool_selection._is_workspace(str(tmp_path)),override=None,)@@ -36,6 +38,53 @@ def test_chat_honors_the_repository_mcp_allowlist(tmp_path) -> None:assert [tool.entry.name for tool in catalog] == ["get_answer", "get_health"]+def _gate_get_health_on(monkeypatch, fact: str) -> None:+ """Make the live get_health entry available only when *fact* is counted."""+ gated = [+ replace(entry, available_when=lambda facts: facts.counts.get(fact, 0) > 0)+ if entry.name == "get_health"+ else entry+ for entry in mcp_tool_registry.entries()+ ]+ monkeypatch.setattr(mcp_tool_registry, "entries", lambda: list(gated))+++def test_chat_hides_a_tool_whose_predicate_fails(tmp_path, monkeypatch) -> None:+ ensure_full_surface()+ _gate_get_health_on(monkeypatch, "findings")+ monkeypatch.setattr(_tool_selection, "_availability_facts", lambda _p: AvailabilityFacts())++ names = {tool.entry.name for tool in chat_tools.get_tool_catalog(str(tmp_path))}++ assert "get_health" not in names+ assert "get_answer" in names+++def test_chat_reevaluates_the_predicate_every_turn(tmp_path, monkeypatch) -> None:+ ensure_full_surface()+ _gate_get_health_on(monkeypatch, "findings")+ facts = {"current": AvailabilityFacts()}+ monkeypatch.setattr(_tool_selection, "_availability_facts", lambda _p: facts["current"])++ before = {tool.entry.name for tool in chat_tools.get_tool_catalog(str(tmp_path))}+ facts["current"] = AvailabilityFacts(counts={"findings": 3})+ after = {tool.entry.name for tool in chat_tools.get_tool_catalog(str(tmp_path))}++ assert "get_health" not in before+ assert "get_health" in after+++async def test_chat_refuses_to_execute_a_gated_tool(tmp_path, monkeypatch) -> None:+ ensure_full_surface()+ _gate_get_health_on(monkeypatch, "findings")+ monkeypatch.setattr(_tool_selection, "_availability_facts", lambda _p: AvailabilityFacts())++ result = await chat_tools.execute_tool("get_health", {}, repo_path=str(tmp_path))++ assert result["error_code"] == "tool_not_enabled"++def test_chat_llm_schemas_are_the_fastmcp_generated_schemas(tmp_path) -> None:ensure_full_surface()schemas = {