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(web): edit the MCP tool surface from the dashboard (#521)

Raghav Chamadiya137463dc108b
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d3c4529c5..99a4be766 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### 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`.
+- **MCP tool surface editor in the dashboard.** The Settings page now lists every tool with its description and lets you toggle the surface per repo, writing the selection back to that repo's `mcp.tools` config. Backed by `GET`/`PATCH /api/mcp/tools`.
### 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/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 3fa55f403..219e3de1d 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -70,6 +70,8 @@ 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.
+**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.
+
---
## Reversible truncation — `_meta.omitted`
diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.py
index 8b73ef8bf..3e0651496 100644
--- a/packages/core/src/repowise/core/repo_config.py
+++ b/packages/core/src/repowise/core/repo_config.py
@@ -39,6 +39,24 @@ def load_repo_config(repo_path: Path | str) -> dict[str, Any]:
return result
+def save_repo_config(repo_path: Path | str, config: dict[str, Any]) -> None:
+ """Write ``config`` to ``.repowise/config.yaml``, replacing the file.
+
+ Callers should round-trip through :func:`load_repo_config` and merge so
+ unrelated keys are preserved; this writer just serializes the final dict.
+ Key order is preserved and flow style is block style, to match the files the
+ CLI writes.
+ """
+ import yaml # type: ignore[import-untyped]
+
+ cfg_dir = get_repowise_dir(repo_path)
+ cfg_dir.mkdir(parents=True, exist_ok=True)
+ (cfg_dir / CONFIG_FILENAME).write_text(
+ yaml.dump(config, default_flow_style=False, sort_keys=False),
+ encoding="utf-8",
+ )
+
+
def _read_flat_scalar(text: str, key: str) -> str | None:
"""Read a top-level scalar from config text before YAML bool coercion."""
for line in text.splitlines():
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 8399a232b..92227ee10 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -47,6 +47,7 @@ from repowise.server.routers import (
health,
jobs,
knowledge_map,
+ mcp,
modules,
overview,
owners,
@@ -407,6 +408,7 @@ def create_app() -> FastAPI:
app.include_router(decisions.router)
app.include_router(chat.router)
app.include_router(providers.router)
+ app.include_router(mcp.router)
app.include_router(costs.router)
app.include_router(security.router)
app.include_router(blast_radius.router)
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 75c400a2a..f73188d4f 100644
--- a/packages/server/src/repowise/server/mcp_server/_tool_selection.py
+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py
@@ -201,3 +201,74 @@ def apply_tool_selection(
registered[name] = tool
return enabled
+
+
+def _tool_description(name: str) -> str:
+ """One-line description for a tool, from its registered FastMCP schema."""
+ tool = (_full_surface or {}).get(name)
+ desc = getattr(tool, "description", "") or ""
+ return desc.strip().split("\n", 1)[0].strip()
+
+
+def describe_tool_surface(repo_path: str | None) -> dict[str, Any]:
+ """Describe the configurable tool surface for a repo (for the settings UI).
+
+ Returns ``is_workspace``, the raw ``override`` currently in config, and one
+ row per registered tool with its name, one-line description, and the flags a
+ UI 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).
+ """
+ entries = mcp_tool_registry.entries()
+ is_workspace = _is_workspace(repo_path)
+ override = _read_config_override(repo_path)
+
+ default_surface = resolve_enabled_tools(
+ entries, is_workspace=is_workspace, override=None
+ )
+ enabled = resolve_enabled_tools(
+ entries, is_workspace=is_workspace, override=override
+ )
+
+ tools = [
+ {
+ "name": e.name,
+ "description": _tool_description(e.name),
+ "default": e.name in default_surface,
+ "requires_workspace": e.requires_workspace,
+ "enabled": e.name in enabled,
+ }
+ for e in sorted(entries, key=lambda e: e.name)
+ ]
+ return {
+ "is_workspace": is_workspace,
+ "override": list(override) if isinstance(override, (list, tuple)) else override,
+ "tools": tools,
+ }
+
+
+def set_tool_override(repo_path: str, tools: str | list[str] | None) -> None:
+ """Persist the ``mcp.tools`` override into ``.repowise/config.yaml``.
+
+ A falsy/empty ``tools`` clears the override (the repo falls back to the
+ default surface); the ``mcp`` block is removed when it becomes empty so the
+ file stays clean. Other config keys are preserved.
+ """
+ from repowise.core.repo_config import load_repo_config, save_repo_config
+
+ config = load_repo_config(repo_path)
+ mcp_cfg = config.get("mcp")
+ if not isinstance(mcp_cfg, dict):
+ mcp_cfg = {}
+
+ if tools:
+ mcp_cfg["tools"] = tools
+ else:
+ mcp_cfg.pop("tools", None)
+
+ if mcp_cfg:
+ config["mcp"] = mcp_cfg
+ else:
+ config.pop("mcp", None)
+
+ save_repo_config(repo_path, config)
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 bd3ca7488..6e0022198 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py
@@ -139,7 +139,7 @@ async def get_execution_flows(
"flows": flows,
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
- hint="Use get_callers_callees on any trace node for detail.",
+ hint="Use get_context(include=['callers','callees']) on any trace node for detail.",
),
}
return result
diff --git a/packages/server/src/repowise/server/routers/mcp.py b/packages/server/src/repowise/server/routers/mcp.py
new file mode 100644
index 000000000..c79cde025
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/mcp.py
@@ -0,0 +1,71 @@
+"""MCP tool-surface endpoints — read and edit which tools a repo exposes.
+
+The MCP server advertises a curated, configurable set of tools (see
+``mcp_server/_tool_selection.py``). These endpoints let the dashboard show that
+surface for a repo and persist a ``mcp.tools`` override into the repo's
+``.repowise/config.yaml``. Changes take effect the next time ``repowise mcp`` is
+started for that repo.
+"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from repowise.server.deps import resolve_request_session_factory, verify_api_key
+from repowise.server.mcp_server._tool_selection import (
+ describe_tool_surface,
+ set_tool_override,
+)
+from repowise.server.schemas import McpToolSurfaceResponse, UpdateMcpToolsRequest
+
+router = APIRouter(
+ prefix="/api/mcp",
+ tags=["mcp"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+async def _repo_path_for(request: Request, repo_id: str | None) -> str | None:
+ """Resolve a repo's on-disk path from its id (None when not found)."""
+ if not repo_id:
+ return None
+ try:
+ factory = resolve_request_session_factory(request)
+ async with get_session(factory) as session:
+ repo = await crud.get_repository(session, repo_id)
+ return repo.local_path if repo else None
+ except Exception:
+ return None
+
+
+def _surface(repo_id: str | None, repo_path: str | None) -> McpToolSurfaceResponse:
+ data = describe_tool_surface(repo_path)
+ return McpToolSurfaceResponse(repo_id=repo_id, **data)
+
+
[email protected]("/tools", response_model=McpToolSurfaceResponse)
+async def get_tool_surface(
+ request: Request, repo_id: str | None = None
+) -> McpToolSurfaceResponse:
+ """Return the configurable tool surface for a repo.
+
+ Pass ``?repo_id=`` so the response reflects that repo's workspace mode and
+ its ``mcp.tools`` override; without it, the default single-repo surface is
+ described.
+ """
+ repo_path = await _repo_path_for(request, repo_id)
+ return _surface(repo_id, repo_path)
+
+
[email protected]("/tools", response_model=McpToolSurfaceResponse)
+async def update_tool_surface(
+ body: UpdateMcpToolsRequest, request: Request
+) -> McpToolSurfaceResponse:
+ """Persist a new ``mcp.tools`` override for a repo and return the surface."""
+ repo_path = await _repo_path_for(request, body.repo_id)
+ if repo_path is None:
+ raise HTTPException(404, f"Repo not found: {body.repo_id}")
+ set_tool_override(repo_path, body.tools)
+ return _surface(body.repo_id, repo_path)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 0288b30ca..32dba7c83 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -95,6 +95,11 @@ from .health import (
CoordinatorHealthResponse,
HealthResponse,
)
+from .mcp import (
+ McpToolInfo,
+ McpToolSurfaceResponse,
+ UpdateMcpToolsRequest,
+)
from .intelligence import (
CallerCalleeEntry,
CallersCalleesResponse,
@@ -264,6 +269,8 @@ __all__ = [
"KnowledgeMapResponse",
"KnowledgeMapSilo",
"KnowledgeMapTarget",
+ "McpToolInfo",
+ "McpToolSurfaceResponse",
"ModuleEdgeResponse",
"ModuleGraphResponse",
"GoverningDecisionRef",
@@ -300,6 +307,7 @@ __all__ = [
"SymbolNodeSummary",
"SymbolResponse",
"TransitiveEntry",
+ "UpdateMcpToolsRequest",
"WebhookResponse",
"WorkspaceCoChangeEntry",
"WorkspaceBlastRadiusResponse",
diff --git a/packages/server/src/repowise/server/schemas/mcp.py b/packages/server/src/repowise/server/schemas/mcp.py
new file mode 100644
index 000000000..c50902ad8
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/mcp.py
@@ -0,0 +1,36 @@
+"""Pydantic models for the configurable MCP tool surface."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel
+
+
+class McpToolInfo(BaseModel):
+ """One tool in the configurable surface, with the flags a UI needs."""
+
+ name: str
+ description: str
+ default: bool
+ requires_workspace: bool
+ enabled: bool
+
+
+class McpToolSurfaceResponse(BaseModel):
+ """The full tool surface for a repo plus its current override."""
+
+ repo_id: str | None = None
+ is_workspace: bool
+ override: list[str] | str | None = None
+ tools: list[McpToolInfo]
+
+
+class UpdateMcpToolsRequest(BaseModel):
+ """Persist a new ``mcp.tools`` override for a repo.
+
+ ``tools`` accepts the same shapes as the config block: a list of explicit
+ names or ``+``/``-`` deltas, the string ``"all"``, or ``null``/empty to
+ clear the override and fall back to the default surface.
+ """
+
+ repo_id: str
+ tools: list[str] | str | None = None
diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsx
index 540d9a0b0..beb9fda18 100644
--- a/packages/web/src/app/settings/page.tsx
+++ b/packages/web/src/app/settings/page.tsx
@@ -3,6 +3,7 @@ import { ConnectionSection } from "@/components/settings/connection-section";
import { ProviderSection } from "@/components/settings/provider-section";
import { WebhookSection } from "@/components/settings/webhook-section";
import { McpSection } from "@/components/settings/mcp-section";
+import { McpToolsSection } from "@/components/settings/mcp-tools-section";
export const metadata: Metadata = { title: "Settings" };
@@ -20,6 +21,7 @@ export default function SettingsPage() {
<ProviderSection />
<WebhookSection />
<McpSection />
+ <McpToolsSection />
<p className="text-xs text-[var(--color-text-tertiary)]">
Per-repository options (sync, exclude patterns, deletion) live on each
diff --git a/packages/web/src/components/settings/mcp-tools-section.tsx b/packages/web/src/components/settings/mcp-tools-section.tsx
new file mode 100644
index 000000000..7bda22a03
--- /dev/null
+++ b/packages/web/src/components/settings/mcp-tools-section.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+} from "@repowise-dev/ui/ui/card";
+import { Badge } from "@repowise-dev/ui/ui/badge";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { Switch } from "@repowise-dev/ui/ui/switch";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@repowise-dev/ui/ui/select";
+import { listRepos } from "@/lib/api/repos";
+import { getMcpToolSurface, updateMcpTools } from "@/lib/api/mcp-tools";
+import type { McpToolSurface } from "@/lib/api/types";
+
+interface RepoOption {
+ id: string;
+ name: string;
+}
+
+function enabledNames(surface: McpToolSurface): Set<string> {
+ return new Set(surface.tools.filter((t) => t.enabled).map((t) => t.name));
+}
+
+export function McpToolsSection() {
+ const [repos, setRepos] = useState<RepoOption[]>([]);
+ const [repoId, setRepoId] = useState<string | null>(null);
+ const [surface, setSurface] = useState<McpToolSurface | null>(null);
+ const [enabled, setEnabled] = useState<Set<string>>(new Set());
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [saved, setSaved] = useState(false);
+
+ // Load the repo list once and pick a default (the primary, else the first).
+ useEffect(() => {
+ listRepos()
+ .then((rows) => {
+ const opts = rows
+ .filter((r) => !r.id.startsWith("ws:"))
+ .map((r) => ({ id: r.id, name: r.name }));
+ setRepos(opts);
+ setRepoId((cur) => cur ?? opts[0]?.id ?? null);
+ if (opts.length === 0) setLoading(false);
+ })
+ .catch((e) => {
+ setError(String(e));
+ setLoading(false);
+ });
+ }, []);
+
+ const loadSurface = useCallback((id: string) => {
+ setLoading(true);
+ setError(null);
+ getMcpToolSurface(id)
+ .then((s) => {
+ setSurface(s);
+ setEnabled(enabledNames(s));
+ })
+ .catch((e) => setError(String(e)))
+ .finally(() => setLoading(false));
+ }, []);
+
+ useEffect(() => {
+ if (repoId) loadSurface(repoId);
+ }, [repoId, loadSurface]);
+
+ function toggle(name: string, on: boolean) {
+ setSaved(false);
+ setEnabled((prev) => {
+ const next = new Set(prev);
+ if (on) next.add(name);
+ else next.delete(name);
+ return next;
+ });
+ }
+
+ const dirty = useMemo(() => {
+ if (!surface) return false;
+ const server = enabledNames(surface);
+ if (server.size !== enabled.size) return true;
+ for (const n of enabled) if (!server.has(n)) return true;
+ return false;
+ }, [surface, enabled]);
+
+ async function save() {
+ if (!surface || !repoId) return;
+ setSaving(true);
+ setError(null);
+ // Store the selection as +/- deltas off the default surface so it stays
+ // correct if the default set changes in a future release.
+ const defaults = new Set(
+ surface.tools.filter((t) => t.default).map((t) => t.name),
+ );
+ const added = [...enabled].filter((n) => !defaults.has(n)).sort();
+ const removed = [...defaults].filter((n) => !enabled.has(n)).sort();
+ const tools = [...added.map((n) => `+${n}`), ...removed.map((n) => `-${n}`)];
+ try {
+ const updated = await updateMcpTools({
+ repo_id: repoId,
+ tools: tools.length ? tools : null,
+ });
+ setSurface(updated);
+ setEnabled(enabledNames(updated));
+ setSaved(true);
+ } catch (e) {
+ setError(String(e));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base">MCP tool surface</CardTitle>
+ <CardDescription>
+ Choose which tools the MCP server exposes for a repo. Changes are saved
+ to its <code className="font-mono">.repowise/config.yaml</code> and take
+ effect the next time you start <code className="font-mono">repowise mcp</code>{" "}
+ for that repo.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {repos.length === 0 && !loading && (
+ <p className="text-sm text-[var(--color-text-tertiary)]">
+ No indexed repos found. Run <code className="font-mono">repowise init</code>{" "}
+ first.
+ </p>
+ )}
+
+ {repos.length > 1 && (
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-[var(--color-text-secondary)]">Repo</span>
+ <Select value={repoId ?? undefined} onValueChange={setRepoId}>
+ <SelectTrigger className="w-56">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {repos.map((r) => (
+ <SelectItem key={r.id} value={r.id}>
+ {r.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+
+ {surface && !loading && (
+ <>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {surface.is_workspace
+ ? "Workspace mode — workspace-only tools are available."
+ : "Single-repo mode — workspace-only tools are unavailable here."}
+ </p>
+
+ <div className="divide-y divide-[var(--color-border-default)] rounded border border-[var(--color-border-default)]">
+ {surface.tools.map((tool) => {
+ const locked = tool.requires_workspace && !surface.is_workspace;
+ return (
+ <div
+ key={tool.name}
+ className="flex items-start gap-3 px-3 py-2.5"
+ >
+ <Switch
+ checked={enabled.has(tool.name)}
+ disabled={locked || saving}
+ onCheckedChange={(v) => toggle(tool.name, v)}
+ className="mt-0.5"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <code className="font-mono text-sm">{tool.name}</code>
+ {tool.requires_workspace && (
+ <Badge variant="outline" className="text-[10px]">
+ workspace
+ </Badge>
+ )}
+ {!tool.default && !tool.requires_workspace && (
+ <Badge variant="outline" className="text-[10px]">
+ opt-in
+ </Badge>
+ )}
+ </div>
+ {tool.description && (
+ <p className="text-xs text-[var(--color-text-tertiary)] mt-0.5">
+ {tool.description}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ <div className="flex items-center gap-3">
+ <Button onClick={save} disabled={!dirty || saving} size="sm">
+ {saving ? "Saving…" : "Save"}
+ </Button>
+ {saved && !dirty && (
+ <span className="text-sm text-[var(--color-fresh)]">Saved</span>
+ )}
+ {dirty && (
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ Unsaved changes
+ </span>
+ )}
+ </div>
+ </>
+ )}
+
+ {error && <p className="text-sm text-[var(--color-error)]">{error}</p>}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/web/src/lib/api/mcp-tools.ts b/packages/web/src/lib/api/mcp-tools.ts
new file mode 100644
index 000000000..18c35e82e
--- /dev/null
+++ b/packages/web/src/lib/api/mcp-tools.ts
@@ -0,0 +1,17 @@
+import { apiGet, apiPatch } from "./client";
+import type { McpToolSurface, UpdateMcpToolsRequest } from "./types";
+
+/** Fetch the configurable MCP tool surface for a repo. */
+export async function getMcpToolSurface(repoId?: string): Promise<McpToolSurface> {
+ return apiGet<McpToolSurface>(
+ "/api/mcp/tools",
+ repoId ? { repo_id: repoId } : undefined,
+ );
+}
+
+/** Persist a new `mcp.tools` override for a repo and return the updated surface. */
+export async function updateMcpTools(
+ body: UpdateMcpToolsRequest,
+): Promise<McpToolSurface> {
+ return apiPatch<McpToolSurface>("/api/mcp/tools", body);
+}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index e3b7d202b..06f97d7c1 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -19,4 +19,5 @@ export * from "./types/decisions";
export * from "./types/chat";
export * from "./types/workspace";
export * from "./types/ownership";
+export * from "./types/mcp";
export * from "./types/misc";
diff --git a/packages/web/src/lib/api/types/mcp.ts b/packages/web/src/lib/api/types/mcp.ts
new file mode 100644
index 000000000..01de3de7f
--- /dev/null
+++ b/packages/web/src/lib/api/types/mcp.ts
@@ -0,0 +1,23 @@
+// ---------------------------------------------------------------------------
+// MCP tool surface
+// ---------------------------------------------------------------------------
+
+export interface McpToolInfo {
+ name: string;
+ description: string;
+ default: boolean;
+ requires_workspace: boolean;
+ enabled: boolean;
+}
+
+export interface McpToolSurface {
+ repo_id: string | null;
+ is_workspace: boolean;
+ override: string[] | string | null;
+ tools: McpToolInfo[];
+}
+
+export interface UpdateMcpToolsRequest {
+ repo_id: string;
+ tools: string[] | string | null;
+}
diff --git a/tests/unit/server/test_mcp_tools_router.py b/tests/unit/server/test_mcp_tools_router.py
new file mode 100644
index 000000000..85f6ec484
--- /dev/null
+++ b/tests/unit/server/test_mcp_tools_router.py
@@ -0,0 +1,107 @@
+"""Tests for the MCP tool-surface REST endpoints."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.mcp_server._tool_selection import (
+ describe_tool_surface,
+ set_tool_override,
+)
+
+
+def test_describe_tool_surface_single_repo(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+ surface = describe_tool_surface(str(tmp_path))
+
+ assert surface["is_workspace"] is False
+ assert surface["override"] is None
+ names = {t["name"] for t in surface["tools"]}
+ # Core tools present and enabled; workspace-only present but disabled.
+ assert {"get_answer", "get_context", "get_blast_radius"} <= names
+ by_name = {t["name"]: t for t in surface["tools"]}
+ assert by_name["get_answer"]["enabled"] is True
+ assert by_name["get_blast_radius"]["requires_workspace"] is True
+ assert by_name["get_blast_radius"]["enabled"] is False
+ # Opt-in tools registered but off by default.
+ assert by_name["get_execution_flows"]["default"] is False
+ assert by_name["get_execution_flows"]["enabled"] is False
+ # Every tool carries a one-line description.
+ assert all(t["description"] for t in surface["tools"])
+
+
+def test_set_tool_override_opt_in_and_clear(tmp_path):
+ (tmp_path / ".repowise").mkdir()
+
+ set_tool_override(str(tmp_path), ["+get_execution_flows"])
+ surface = describe_tool_surface(str(tmp_path))
+ by_name = {t["name"]: t for t in surface["tools"]}
+ assert by_name["get_execution_flows"]["enabled"] is True
+ assert surface["override"] == ["+get_execution_flows"]
+
+ # Clearing removes the override and the mcp block entirely.
+ set_tool_override(str(tmp_path), None)
+ from repowise.core.repo_config import load_repo_config
+
+ assert "mcp" not in load_repo_config(str(tmp_path))
+ assert describe_tool_surface(str(tmp_path))["override"] is None
+
+
+def test_set_tool_override_preserves_other_config(tmp_path):
+ rw = tmp_path / ".repowise"
+ rw.mkdir()
+ (rw / "config.yaml").write_text("provider: openai\nmodel: gpt-5\n", encoding="utf-8")
+
+ set_tool_override(str(tmp_path), ["+get_dependency_path"])
+
+ from repowise.core.repo_config import load_repo_config
+
+ cfg = load_repo_config(str(tmp_path))
+ assert cfg["provider"] == "openai"
+ assert cfg["model"] == "gpt-5"
+ assert cfg["mcp"]["tools"] == ["+get_dependency_path"]
+
+
+async def test_router_get_and_patch(tmp_path, monkeypatch):
+ """The REST endpoints resolve a repo path, read, and persist the surface."""
+ from repowise.server.routers import mcp as mcp_router
+
+ (tmp_path / ".repowise").mkdir()
+
+ async def fake_repo_path(_request, repo_id):
+ return str(tmp_path) if repo_id == "r1" else None
+
+ monkeypatch.setattr(mcp_router, "_repo_path_for", fake_repo_path)
+
+ got = await mcp_router.get_tool_surface(request=None, repo_id="r1")
+ assert got.repo_id == "r1"
+ assert any(t.name == "get_answer" and t.enabled for t in got.tools)
+
+ from repowise.server.schemas import UpdateMcpToolsRequest
+
+ updated = await mcp_router.update_tool_surface(
+ body=UpdateMcpToolsRequest(repo_id="r1", tools=["+get_dependency_path"]),
+ request=None,
+ )
+ assert any(t.name == "get_dependency_path" and t.enabled for t in updated.tools)
+
+
+async def test_router_patch_unknown_repo_404(monkeypatch):
+ from fastapi import HTTPException
+
+ from repowise.server.routers import mcp as mcp_router
+ from repowise.server.schemas import UpdateMcpToolsRequest
+
+ async def fake_repo_path(_request, repo_id):
+ return None
+
+ monkeypatch.setattr(mcp_router, "_repo_path_for", fake_repo_path)
+
+ with pytest.raises(HTTPException) as exc:
+ await mcp_router.update_tool_surface(
+ body=UpdateMcpToolsRequest(repo_id="missing", tools=None),
+ request=None,
+ )
+ assert exc.value.status_code == 404