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.

feat(mcp): make the tool surface context-aware and configurable (#520)

Raghav Chamadiya22c58152b332
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 506ecb28b..d3c4529c5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,6 +11,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- **Configurable MCP tool surface.** The set of tools the MCP server advertises is now configurable. Workspace-only tools (`get_blast_radius`, `get_conformance`, `get_architecture`) are advertised only in workspace mode instead of always, and two extra tools (`get_dependency_path`, `get_execution_flows`) can be opted in. Configure it with an `mcp.tools` block in `.repowise/config.yaml` (`+`/`-` deltas, an explicit allowlist, or `all`) or per launch with `repowise mcp --tools` / `--all`.
+
### Changed
- **Consolidated the MCP tool surface.** Removed six redundant MCP tools (`annotate_file`, `get_callers_callees`, `get_community`, `get_graph_metrics`, `get_architecture_diagram`, `update_decision_records`) whose capabilities are already covered by `get_context(include=[...])` and `get_why`. The MCP server exposes 13 tools: 10 in single-repo mode plus three workspace-only tools (`get_blast_radius`, `get_conformance`, `get_architecture`). Documentation and tool counts across the project were reconciled to match.
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index fd6658aaf..367e2fd74 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -96,6 +96,27 @@ distill:
`commands.enabled: false`, so a rewrite hook installed globally from another
repo stays inert in this one.
+### The `mcp:` block
+
+Controls which tools the MCP server advertises. The default surface is curated
+(10 tools in single-repo mode, plus 3 workspace-only tools in workspace mode);
+this block lets you opt extra tools in or trim the set down. The `repowise mcp
+--tools` / `--all` flags override it for a single launch.
+
+```yaml
+mcp:
+ tools: ["+get_execution_flows", "-get_dead_code"] # adjust the default set
+ # tools: ["get_answer", "get_context"] # or an explicit allowlist
+ # tools: all # or everything available
+```
+
+- `+name` / `-name` entries add to or remove from the default set; an
+ unprefixed list is treated as an explicit allowlist.
+- Opt-in tools are `get_dependency_path` and `get_execution_flows`.
+- Workspace-only tools (`get_blast_radius`, `get_conformance`,
+ `get_architecture`) are added automatically in workspace mode and ignored if
+ named in single-repo mode. See [MCP_TOOLS.md](MCP_TOOLS.md#configuring-the-tool-surface).
+
---
## LLM providers
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 44551f13f..3fa55f403 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -1,6 +1,6 @@
# MCP Tools Reference
-repowise exposes 9 tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions.
+repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence — dependency graph, git history, documentation, and architectural decisions. A single-repo server advertises 10 tools by default; workspace mode adds 3 more automatically. The surface is configurable — see [Configuring the tool surface](#configuring-the-tool-surface).
**Start the MCP server:**
@@ -27,10 +27,49 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport
| `get_why` | Architectural decisions | Before structural changes |
| `get_dead_code` | Unreachable code | Cleanup tasks |
| `get_health` | Code-health biomarker scores | Before refactoring — find the worst files |
+| `list_repos` | List the repos a server is serving | Discovering workspace repo aliases |
| `get_blast_radius` | Cross-repo downstream impact (workspace only) | Before changing a service other repos consume |
| `get_conformance` | Architecture rule violations + cycles (workspace only) | Auditing or before changing service boundaries |
| `get_architecture` | System coupling, cyclic core, 1-10 architecture score (workspace only) | Gauging overall structure before a cross-service refactor |
+Two further tools are **off by default** and opt-in (see below): `get_dependency_path` (shortest dependency path between two symbols/files) and `get_execution_flows` (top entry points and their call traces).
+
+---
+
+## Configuring the tool surface
+
+The default surface is deliberately small — fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's defaults, whether the server is in workspace mode, and an optional override.
+
+- **Default (single-repo):** the 10 tools above (every tool except the workspace-only three).
+- **Default (workspace):** those 10 plus `get_blast_radius`, `get_conformance`, and `get_architecture`, which are added automatically when the server is started inside a workspace. They are never advertised outside one.
+- **Opt-in tools:** `get_dependency_path` and `get_execution_flows` are registered but off by default. Turn them on per repo.
+
+**Configure it in `.repowise/config.yaml`** under an `mcp.tools` key. Two shapes are supported:
+
+```yaml
+# Adjust the default set with + / - deltas (the common case):
+mcp:
+ tools: ["+get_execution_flows", "-get_dead_code"]
+
+# Or give an explicit allowlist (only these tools):
+mcp:
+ tools: ["get_answer", "get_context", "get_symbol", "search_codebase"]
+
+# Or enable everything available in the current mode:
+mcp:
+ tools: all
+```
+
+**Or per launch on the CLI**, which overrides the config block:
+
+```bash
+repowise mcp --tools "+get_execution_flows" # default set plus one
+repowise mcp --tools "get_answer,get_context" # explicit allowlist
+repowise mcp --all # every available tool
+```
+
+Workspace-only tools named explicitly in single-repo mode are ignored (they cannot do useful work there). Unknown tool names are ignored with a warning.
+
---
## Reversible truncation — `_meta.omitted`
diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
index ab96ed6ff..346b6e2a5 100644
--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
@@ -84,13 +84,38 @@ def _print_network_startup(
default=7338,
help="Port for HTTP/SSE transports (default: 7338).",
)
-def mcp_command(path: str | None, transport: str, port: int) -> None:
+ "--tools",
+ default=None,
+ help=(
+ "Override which tools are exposed. A comma-separated list is an "
+ "explicit allowlist; prefix names with + or - to adjust the default "
+ "set (e.g. '+get_dependency_path,-get_dead_code'). Overrides the "
+ "mcp.tools config block."
+ ),
+)
+ "--all",
+ "all_tools",
+ is_flag=True,
+ default=False,
+ help="Expose every available tool, including opt-in and workspace tools.",
+)
+def mcp_command(
+ path: str | None,
+ transport: str,
+ port: int,
+ tools: str | None,
+ all_tools: bool,
+) -> None:
"""Start the MCP server for editor integration.
- Exposes 13 tools for querying the repowise wiki via the MCP protocol
- (ten in single-repo mode, plus three workspace-only tools in workspace
- mode). Supports stdio (for Claude Code, Codex, Cursor, Cline), streamable
- HTTP, and legacy SSE transports.
+ Exposes a curated set of tools for querying the repowise wiki via the MCP
+ protocol: ten in single-repo mode, plus three workspace-only tools in
+ workspace mode. Two more (get_dependency_path, get_execution_flows) are
+ opt-in via ``--tools`` or the ``mcp.tools`` config block. Supports stdio
+ (for Claude Code, Codex, Cursor, Cline), streamable HTTP, and legacy SSE
+ transports.
Loads ``<repo>/.repowise/.env`` into the environment before starting so
that MCP tools (e.g. ``get_answer``) can resolve the configured LLM
@@ -100,8 +125,9 @@ def mcp_command(path: str | None, transport: str, port: int) -> None:
repowise mcp # stdio, current directory
repowise mcp /path/to/repo # stdio, specific repo
+ repowise mcp --tools +get_execution_flows # default set plus one
+ repowise mcp --all # every available tool
repowise mcp --transport streamable-http # HTTP on port 7338
- repowise mcp --transport sse # SSE on port 7338
"""
if path is None:
repo_path = find_repowise_repo_root(Path.cwd()) or resolve_repo_path(None)
@@ -125,8 +151,11 @@ def mcp_command(path: str | None, transport: str, port: int) -> None:
from repowise.server.mcp_server import run_mcp
+ tools_override: str | None = "all" if all_tools else tools
+
run_mcp(
transport=transport,
repo_path=str(repo_path),
port=port,
+ tools=tools_override,
)
diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.py
index 8049ff7cb..9e7dcf11b 100644
--- a/packages/core/src/repowise/core/registry/__init__.py
+++ b/packages/core/src/repowise/core/registry/__init__.py
@@ -19,7 +19,7 @@ their own. The OSS CLI and MCP server use the module-level instances.
from __future__ import annotations
from .cli_registry import CLIRegistry, cli_registry, register_command
-from .mcp_tool_registry import MCPToolRegistry, mcp_tool_registry
+from .mcp_tool_registry import MCPToolRegistry, ToolEntry, mcp_tool_registry
from .pipeline_hooks import (
HookPhase,
HookProgressCallback,
@@ -34,6 +34,7 @@ __all__ = [
"HookProgressCallback",
"MCPToolRegistry",
"PipelineHookRegistry",
+ "ToolEntry",
"cli_registry",
"mcp_tool_registry",
"pipeline_hooks",
diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.py
index 4bc39f442..369376f58 100644
--- a/packages/core/src/repowise/core/registry/mcp_tool_registry.py
+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py
@@ -32,40 +32,67 @@ Usage::
from __future__ import annotations
from collections.abc import Callable
+from dataclasses import dataclass
from typing import Any
+@dataclass(frozen=True)
+class ToolEntry:
+ """A registered tool plus the metadata that drives surface selection.
+
+ ``name`` is the tool's wire name (the function ``__name__``, which is
+ what FastMCP registers and what the selection layer removes by). ``default``
+ marks whether the tool is part of the curated default surface; opt-in tools
+ set it ``False``. ``requires_workspace`` marks tools that only do useful
+ work in workspace mode, so they are hidden from single-repo servers.
+ """
+
+ fn: Callable[..., Any]
+ name: str
+ default: bool = True
+ requires_workspace: bool = False
+
+
class MCPToolRegistry:
"""Holds tool callables until :meth:`apply` attaches them to a server."""
def __init__(self) -> None:
- self._tools: list[Callable[..., Any]] = []
+ self._entries: list[ToolEntry] = []
self._applied_to: list[Any] = []
def register(
self,
*args: Any,
+ default: bool = True,
+ requires_workspace: bool = False,
**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. Keyword arguments
- are currently ignored; they exist as a forward-compat hook for
- future ``description=`` / ``name=`` overrides.
+ ``@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
+ for future ``description=`` / ``name=`` overrides and ignored.
"""
+
+ def _add(fn: Callable[..., Any]) -> Callable[..., Any]:
+ self._entries.append(
+ ToolEntry(
+ fn=fn,
+ name=fn.__name__,
+ default=default,
+ requires_workspace=requires_workspace,
+ )
+ )
+ return fn
+
# Bare-decorator form: @mcp_tool_registry.register
if len(args) == 1 and callable(args[0]) and not kwargs:
- fn = args[0]
- self._tools.append(fn)
- return fn
+ return _add(args[0])
# Called form: @mcp_tool_registry.register()
- def _decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
- self._tools.append(fn)
- return fn
-
- return _decorator
+ return _add
# FastMCP-style alias so existing tool modules can swap
# ``from ._server import mcp`` to
@@ -93,23 +120,27 @@ class MCPToolRegistry:
"""
if mcp in self._applied_to:
return
- for fn in self._tools:
- wrapped = middleware(fn) if middleware is not None else fn
+ for entry in self._entries:
+ wrapped = middleware(entry.fn) if middleware is not None else entry.fn
mcp.tool()(wrapped)
self._applied_to.append(mcp)
def reset(self) -> None:
"""Drop every registered tool. Used by tests."""
- self._tools.clear()
+ self._entries.clear()
self._applied_to.clear()
def tools(self) -> list[Callable[..., Any]]:
"""Return every registered tool function. Used by tests."""
- return list(self._tools)
+ return [entry.fn for entry in self._entries]
+
+ def entries(self) -> list[ToolEntry]:
+ """Return every registered tool with its selection metadata."""
+ return list(self._entries)
mcp_tool_registry = MCPToolRegistry()
"""Process-wide default registry used by the OSS MCP server."""
-__all__ = ["MCPToolRegistry", "mcp_tool_registry"]
+__all__ = ["MCPToolRegistry", "ToolEntry", "mcp_tool_registry"]
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 72fb7c597..c96d8254b 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -1,9 +1,12 @@
-"""repowise MCP Server — 13 tools for AI coding assistants.
+"""repowise MCP Server — a curated, configurable tool surface for AI agents.
-Ten tools are available in single-repo mode (get_answer, get_context,
+By default a single-repo server exposes ten tools (get_answer, get_context,
get_symbol, search_codebase, get_overview, get_risk, get_why, get_dead_code,
get_health, list_repos); three more (get_blast_radius, get_conformance,
-get_architecture) are workspace-only.
+get_architecture) are added automatically in workspace mode. Two further tools
+(get_dependency_path, get_execution_flows) are registered but off by default and
+can be opted in via the ``mcp.tools`` config block or the ``repowise mcp
+--tools`` flag. The selection layer lives in :mod:`._tool_selection`.
Exposes the full repowise wiki as queryable tools via the MCP protocol.
Supports stdio transport (Claude Code, Cursor, Cline), streamable HTTP, and
@@ -42,12 +45,17 @@ from repowise.server.mcp_server._server import (
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_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_repos import list_repos
@@ -61,6 +69,11 @@ from repowise.server.mcp_server.tool_why import get_why
# ledger. The wrapper is signature-preserving, so tool schemas are unchanged.
_mcp_tool_registry.apply(mcp, middleware=_savings_instrument)
+# 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)
+
# ---------------------------------------------------------------------------
# Backward-compatible access to _state globals.
#
@@ -121,6 +134,8 @@ __all__ = [
"get_conformance",
"get_context",
"get_dead_code",
+ "get_dependency_path",
+ "get_execution_flows",
"get_health",
"get_overview",
"get_risk",
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index 138c18823..2e6cf2247 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -403,9 +403,19 @@ mcp = FastMCP(
# ---------------------------------------------------------------------------
-def create_mcp_server(repo_path: str | None = None) -> FastMCP:
- """Create and return the MCP server instance, optionally scoped to a repo."""
+def create_mcp_server(
+ repo_path: str | None = None,
+ tools: str | list[str] | None = None,
+) -> FastMCP:
+ """Create and return the MCP server instance, optionally scoped to a repo.
+
+ ``tools`` is an optional surface override (an explicit allowlist, ``+``/``-``
+ deltas, or ``"all"``); when omitted the ``mcp.tools`` config block is used.
+ """
_state._repo_path = repo_path
+ from repowise.server.mcp_server._tool_selection import apply_tool_selection
+
+ apply_tool_selection(mcp, repo_path=repo_path, override=tools)
return mcp
@@ -413,9 +423,18 @@ def run_mcp(
transport: str = "stdio",
repo_path: str | None = None,
port: int = 7338,
+ tools: str | list[str] | None = None,
) -> None:
- """Run the MCP server with the specified transport."""
+ """Run the MCP server with the specified transport.
+
+ ``tools`` overrides which tools are advertised (see
+ :func:`repowise.server.mcp_server._tool_selection.apply_tool_selection`);
+ when omitted, the ``mcp.tools`` config block is honoured.
+ """
_state._repo_path = repo_path
+ from repowise.server.mcp_server._tool_selection import apply_tool_selection
+
+ apply_tool_selection(mcp, repo_path=repo_path, override=tools)
if transport == "sse":
mcp.settings.port = port
diff --git a/packages/server/src/repowise/server/mcp_server/_tool_selection.py b/packages/server/src/repowise/server/mcp_server/_tool_selection.py
new file mode 100644
index 000000000..75c400a2a
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py
@@ -0,0 +1,203 @@
+"""Selection of which MCP tools a server advertises.
+
+The registry attaches *every* tool to the FastMCP instance at import time. 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.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterable, Sequence
+from pathlib import Path
+from typing import Any
+
+from repowise.core.registry import ToolEntry, mcp_tool_registry
+
+_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"
+
+# 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
+# re-add a tool a previous call removed (the FastMCP manager only supports
+# removal, not re-registration).
+_full_surface: dict[str, Any] | None = None
+
+
+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.
+ """
+ global _full_surface
+ if _full_surface is not None:
+ return
+ manager = getattr(mcp, "_tool_manager", None)
+ registered = getattr(manager, "_tools", None)
+ if registered:
+ _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.
+ - 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)}
+
+ 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:
+ return None
+ try:
+ from repowise.core.repo_config import load_repo_config
+
+ mcp_cfg = load_repo_config(repo_path).get("mcp") or {}
+ if isinstance(mcp_cfg, dict):
+ return mcp_cfg.get("tools")
+ except Exception:
+ _log.debug("Failed to read mcp.tools from config", exc_info=True)
+ return None
+
+
+def _is_workspace(repo_path: str | None) -> bool:
+ if not repo_path:
+ return False
+ try:
+ from repowise.core.workspace.config import find_workspace_root
+
+ return find_workspace_root(Path(repo_path)) is not None
+ except Exception:
+ _log.debug("Workspace detection failed during tool selection", exc_info=True)
+ return False
+
+
+def apply_tool_selection(
+ mcp: Any,
+ *,
+ repo_path: str | None,
+ override: str | Sequence[str] | None = None,
+) -> set[str]:
+ """Trim *mcp*'s registered tools to the resolved surface.
+
+ Resolves the enabled set from the registry metadata, the workspace mode of
+ ``repo_path``, and ``override`` (which falls back to the ``mcp.tools`` config
+ 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.
+ """
+ if override is None:
+ override = _read_config_override(repo_path)
+
+ enabled = resolve_enabled_tools(
+ mcp_tool_registry.entries(),
+ is_workspace=_is_workspace(repo_path),
+ override=override,
+ )
+
+ manager = getattr(mcp, "_tool_manager", None)
+ registered = getattr(manager, "_tools", None)
+ if registered is None:
+ return enabled
+
+ # 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.
+ source = _full_surface if _full_surface is not None else dict(registered)
+ registered.clear()
+ for name, tool in source.items():
+ if name in enabled:
+ registered[name] = tool
+
+ return enabled
diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
index b905f680b..829b7e825 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py
@@ -20,7 +20,7 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
_MCP_CORE_MEMBER_LIMIT = 25
[email protected](requires_workspace=True)
async def get_architecture() -> dict[str, Any]:
"""Workspace architecture metrics — coupling, core, and a 1-10 score.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
index 582f4866b..b2bbe922b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py
@@ -22,7 +22,7 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
_MCP_IMPACTED_LIMIT = 25
[email protected](requires_workspace=True)
async def get_blast_radius(
targets: list[str],
max_depth: int = 3,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
index 7db17b98d..5cf38c35e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py
@@ -21,7 +21,7 @@ _MCP_VIOLATION_LIMIT = 25
_MCP_CYCLE_LIMIT = 25
[email protected](requires_workspace=True)
async def get_conformance(repo: str | None = None) -> dict[str, Any]:
"""Architecture conformance — dependency-rule violations + cycles.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
index 8a8a74ed6..3d2e91960 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
@@ -24,7 +24,7 @@ from repowise.server.mcp_server._helpers import (
from repowise.core.registry import mcp_tool_registry as mcp
[email protected](default=False)
async def get_dependency_path(source: str, target: str, repo: str | None = None) -> dict:
"""Find how two files/modules are connected in the dependency graph.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.py
index a46694d04..bd3ca7488 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py
@@ -35,7 +35,7 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.core.registry import mcp_tool_registry as mcp
[email protected](default=False)
async def get_execution_flows(
top_n: int = 10,
max_depth: int = 8,
diff --git a/tests/unit/cli/test_mcp_transport.py b/tests/unit/cli/test_mcp_transport.py
index 726c6c6d2..d9ba012db 100644
--- a/tests/unit/cli/test_mcp_transport.py
+++ b/tests/unit/cli/test_mcp_transport.py
@@ -18,6 +18,34 @@ def test_mcp_help_lists_streamable_http_transport() -> None:
assert "HTTP/SSE" in result.output
+def test_mcp_cli_passes_tools_override(monkeypatch, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ captured: dict[str, object] = {}
+ monkeypatch.setattr(
+ "repowise.server.mcp_server.run_mcp", lambda **kw: captured.update(kw)
+ )
+
+ result = CliRunner().invoke(
+ cli, ["mcp", str(tmp_path), "--tools", "+get_execution_flows,-get_dead_code"]
+ )
+
+ assert result.exit_code == 0
+ assert captured["tools"] == "+get_execution_flows,-get_dead_code"
+
+
+def test_mcp_cli_all_flag_overrides_tools(monkeypatch, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ captured: dict[str, object] = {}
+ monkeypatch.setattr(
+ "repowise.server.mcp_server.run_mcp", lambda **kw: captured.update(kw)
+ )
+
+ result = CliRunner().invoke(cli, ["mcp", str(tmp_path), "--all", "--tools", "get_answer"])
+
+ assert result.exit_code == 0
+ assert captured["tools"] == "all"
+
+
def test_mcp_cli_accepts_streamable_http_transport(
monkeypatch,
tmp_path: Path,
@@ -48,6 +76,7 @@ def test_mcp_cli_accepts_streamable_http_transport(
"transport": "streamable-http",
"repo_path": str(tmp_path.resolve()),
"port": 7339,
+ "tools": None,
}
@@ -98,6 +127,7 @@ def test_mcp_cli_streamable_http_prints_workspace_summary(
"transport": "streamable-http",
"repo_path": str(workspace.resolve()),
"port": 7341,
+ "tools": None,
}
diff --git a/tests/unit/server/mcp/test_tool_selection.py b/tests/unit/server/mcp/test_tool_selection.py
new file mode 100644
index 000000000..3341c50dd
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_selection.py
@@ -0,0 +1,132 @@
+"""Tests for the configurable MCP tool surface (_tool_selection)."""
+
+from __future__ import annotations
+
+import 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: 3 plain defaults, 1 workspace-only, 1 opt-in.
+CATALOG = [
+ ToolEntry(_fn("get_answer"), "get_answer"),
+ ToolEntry(_fn("get_context"), "get_context"),
+ ToolEntry(_fn("list_repos"), "list_repos"),
+ ToolEntry(_fn("get_blast_radius"), "get_blast_radius", requires_workspace=True),
+ 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", "list_repos"}
+
+
+def test_default_workspace_adds_workspace_only():
+ enabled = resolve_enabled_tools(CATALOG, is_workspace=True)
+ assert enabled == {"get_answer", "get_context", "list_repos", "get_blast_radius"}
+
+
+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", "list_repos", "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", "list_repos", "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",
+ "list_repos",
+ "get_dependency_path",
+ }
+
+
+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", "list_repos"}
+
+
+def test_empty_override_falls_back_to_default():
+ assert resolve_enabled_tools(CATALOG, is_workspace=False, override="") == (
+ resolve_enabled_tools(CATALOG, is_workspace=False)
+ )
+
+
+# --- live FastMCP trimming -------------------------------------------------
+
+
+async def test_apply_trims_and_restores_live_server(tmp_path):
+ """apply_tool_selection trims the real server and can rebuild the full set."""
+ import repowise.server.mcp_server as mcp_mod
+ from repowise.server.mcp_server import _tool_selection
+ from repowise.server.mcp_server._tool_selection import apply_tool_selection
+
+ mcp = mcp_mod.mcp
+ (tmp_path / ".repowise").mkdir()
+
+ async def names() -> set[str]:
+ return {t.name for t in await mcp.list_tools()}
+
+ try:
+ # Single-repo default: workspace-only and opt-in tools are hidden.
+ apply_tool_selection(mcp, repo_path=str(tmp_path), override=None)
+ single = await names()
+ assert "get_health" in single
+ assert "get_blast_radius" not in single
+ assert "get_dependency_path" not in single
+
+ # Opt in to one tool; it reappears.
+ apply_tool_selection(mcp, repo_path=str(tmp_path), override="+get_dependency_path")
+ assert "get_dependency_path" in await names()
+ finally:
+ # Restore the full surface so other tests see every tool, including the
+ # workspace-only ones an "all" override on a non-workspace path omits.
+ if _tool_selection._full_surface is not None:
+ mcp._tool_manager._tools = dict(_tool_selection._full_surface)