Skip to content

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

fix(mcp): clarify five workspace error replies (#3943)

jungwonenjoyericl01f1f9146c1b
diff --git a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
index 611608dba..a0abad0d9 100644
--- a/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
+++ b/packages/server/src/repowise/server/mcp_server/_workspace_routing.py
@@ -38,7 +38,7 @@ import os
import re
from collections.abc import Awaitable, Callable, Collection, Sequence
from dataclasses import dataclass, replace
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from typing import Any
from repowise.server.mcp_server import _state
@@ -166,9 +166,32 @@ _MISS_HINT = (
)
+def _miss_hint(target: str) -> str:
+ """Name an unknown repo prefix; keep the search hint for ordinary misses."""
+ registry = _state._registry
+ if registry is None:
+ return _MISS_HINT
+ head, sep, rest = _LINE_SUFFIX_RE.sub("", target).partition(":")
+ head = head.strip()
+ if not head or not sep or not rest:
+ return _MISS_HINT
+ # Symbol references and target kinds are not repository prefixes.
+ if rest.startswith(":") or head.casefold() in _TARGET_KINDS:
+ return _MISS_HINT
+ # A path separator or Windows drive identifies a filesystem path.
+ if "/" in head or "\\" in head:
+ return _MISS_HINT
+ if Path(target).is_absolute() or PureWindowsPath(target).drive:
+ return _MISS_HINT
+ aliases = registry.get_all_aliases()
+ if head.casefold() in {alias.casefold() for alias in aliases}:
+ return _MISS_HINT
+ return f"Unknown repository alias '{head}'. Available aliases: {', '.join(aliases)}."
+
+
def hint_misses(response: dict[str, Any], routes: list[Route]) -> None:
- """Add the search hint to a not-found answer for each target no repo has."""
- missed = {r.target for r in routes if r.missed}
+ """Add an alias or search hint to each missed target's not-found answer."""
+ missed = {r.target: _miss_hint(r.target) for r in routes if r.missed}
if not missed:
return
cards = response.get("targets")
@@ -177,12 +200,12 @@ def hint_misses(response: dict[str, Any], routes: list[Route]) -> None:
if key in missed and isinstance(card, dict) and (
card.get("error") or card.get("unresolved_reason")
):
- card["hint"] = _MISS_HINT
+ card["hint"] = missed[key]
for item in response.get("unresolved") or ():
if isinstance(item, dict) and item.get("target") in missed:
- item["hint"] = _MISS_HINT
+ item["hint"] = missed[item["target"]]
if response.get("error") and not isinstance(cards, dict):
- response["hint"] = _MISS_HINT
+ response["hint"] = " ".join(dict.fromkeys(missed.values()))
def rekey_targets(response: dict[str, Any], routes: list[Route]) -> None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
index 5a0b2238f..ff9744c64 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
@@ -519,12 +519,13 @@ def _default_shape(
payload.pop("candidates", None)
_prune_fallback_targets(payload, raw_fallbacks)
- if not str(payload.get("answer") or "").strip():
- payload["answer"] = str(payload.get("note") or "No grounded answer was found.")
- payload.setdefault(
- "next_action_hint",
- "Use the first emitted evidence row; refine the question if it does not resolve the issue.",
- )
+ if not payload.get("error"):
+ if not str(payload.get("answer") or "").strip():
+ payload["answer"] = str(payload.get("note") or "No grounded answer was found.")
+ payload.setdefault(
+ "next_action_hint",
+ "Use the first emitted evidence row; refine the question if it does not resolve the issue.",
+ )
_RANKED_RATIONALE_CHARS = 200
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
index 9e75035dd..fa8b6ba25 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
@@ -67,7 +67,8 @@ async def _score_change(
except ValueError as exc:
return None, {"error": str(exc)}
except subprocess.CalledProcessError as exc:
- detail = (exc.stderr or "").strip() or str(exc)
+ detail = (exc.stderr or "").partition("\nUse '--' to separate paths from revisions")[0]
+ detail = detail.strip() or str(exc)
return None, {"error": f"Could not read change {revspec or 'HEAD'!r}: {detail}"}
except subprocess.TimeoutExpired:
return None, {"error": f"git timed out reading change {revspec or 'HEAD'!r}."}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
index 8be64568e..7dec43f08 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
@@ -115,6 +115,11 @@ async def _finding_detail_response(
targets=[match.file_path] if match else None,
),
}
+ if match is None and finding_id.startswith(("fix", _ACTION_ID_PREFIX)):
+ result["hint"] = (
+ "Pass fix_first ids (fix1_...) and next_actions ids (act_...) "
+ "as fix_id, not finding_id."
+ )
await _attach_repository_analysis_meta(session, repository, result["_meta"])
return result
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/tool.py b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
index b713cafdc..f1c3a99a8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/tool.py
@@ -73,7 +73,9 @@ async def get_why(
# --- repo="all": search decisions across ALL repos ---
if repo == "all":
if not query:
- return _unsupported_repo_all("get_why (health dashboard)")
+ response = _unsupported_repo_all("get_why (health dashboard)")
+ response["error"] += " To search all repositories, pass a query."
+ return response
return _stamp_answer_basis(await _why_workspace_search(query))
# --- Mode 1: No query → the targets, or the health dashboard ---
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index e482412f3..98d2717a2 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -40,6 +40,26 @@ async def test_git_failure_reports_the_revspec_and_git_stderr(monkeypatch):
assert result == {"error": "Could not read change 'deadbeef': fatal: bad object deadbeef"}
[email protected]("newline", ["\n", "\r\n"])
+async def test_unknown_ref_drops_git_command_line_advice(monkeypatch, newline):
+ fatal = (
+ "fatal: ambiguous argument 'not-a-ref': "
+ "unknown revision or path not in the working tree."
+ )
+ stderr = newline.join([
+ fatal,
+ "Use '--' to separate paths from revisions, like this:",
+ "'git <command> [<revision>...] -- [<file>...]'",
+ "",
+ ])
+ exc = subprocess.CalledProcessError(128, ["git"], stderr=stderr)
+
+ result = await _score_raising(monkeypatch, exc, "not-a-ref")
+
+ assert result == {"error": f"Could not read change 'not-a-ref': {fatal}"}
+
+
@pytest.mark.asyncio
async def test_git_failure_without_stderr_falls_back_to_the_exception_text(monkeypatch):
exc = subprocess.CalledProcessError(1, ["git", "diff"], stderr="")
diff --git a/tests/unit/server/mcp/test_why_evidence_contract.py b/tests/unit/server/mcp/test_why_evidence_contract.py
index a029372ee..af59a1218 100644
--- a/tests/unit/server/mcp/test_why_evidence_contract.py
+++ b/tests/unit/server/mcp/test_why_evidence_contract.py
@@ -590,7 +590,8 @@ async def test_no_decision_and_unsupported_modes_remain_compatible(
assert unsupported == {
"error": (
"repo='all' is not supported for get_why (health dashboard). "
- "Specify a repo alias instead. Available: []"
+ "Specify a repo alias instead. Available: [] "
+ "To search all repositories, pass a query."
)
}
diff --git a/tests/unit/server/mcp/test_workspace_error_guidance.py b/tests/unit/server/mcp/test_workspace_error_guidance.py
new file mode 100644
index 000000000..961d3a6eb
--- /dev/null
+++ b/tests/unit/server/mcp/test_workspace_error_guidance.py
@@ -0,0 +1,170 @@
+"""Workspace input errors give actionable hints without inventing search results."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.server.mcp_server import (
+ _state,
+ get_answer,
+ get_change_risk,
+ get_health,
+ get_risk,
+ get_why,
+)
+from repowise.server.mcp_server._workspace_routing import _MISS_HINT, Route, hint_misses
+from repowise.server.mcp_server.tool_answer.projection import project_answer_payload
+from tests.unit.server.test_mcp_workspace import workspace_mcp as workspace_mcp
+
+
[email protected]("workspace_mcp")
+class TestWorkspaceErrors:
+ async def test_why_dashboard_names_both_supported_alternatives(self):
+ result = await get_why(repo="all")
+
+ assert result["error"] == (
+ "repo='all' is not supported for get_why (health dashboard). "
+ "Specify a repo alias instead. Available: ['backend', 'frontend'] "
+ "To search all repositories, pass a query."
+ )
+
+ async def test_why_all_still_accepts_a_query(self):
+ result = await get_why(query="why is authentication used", repo="all")
+
+ assert "error" not in result
+
+ async def test_why_reference_lookup_keeps_its_existing_error(self):
+ result = await get_why(id="decision_x", repo="all")
+
+ assert result["error"] == (
+ "repo='all' is not supported for get_why (reference lookup). "
+ "Specify a repo alias instead. Available: ['backend', 'frontend']"
+ )
+
+ @pytest.mark.parametrize("include", [None, ["evidence"]])
+ async def test_answer_error_has_no_fallback_or_evidence_hint(self, include):
+ result = await get_answer("how does routing work", repo="all", include=include)
+
+ assert result["error"] == (
+ "repo='all' is not supported for get_answer. "
+ "Specify a repo alias instead. Available: ['backend', 'frontend']"
+ )
+ assert "answer" not in result
+ assert "next_action_hint" not in result
+
+ async def test_risk_names_unknown_alias_and_keeps_other_targets(self):
+ result = await get_risk(targets=["zzz:foo.py", "src/probe.py", "missing.py"])
+
+ cards = result["targets"]
+ assert cards["zzz:foo.py"]["resolved"] is False
+ assert cards["zzz:foo.py"]["hint"] == (
+ "Unknown repository alias 'zzz'. Available aliases: backend, frontend."
+ )
+ assert cards["src/probe.py"].get("unresolved_reason") is None
+ assert cards["missing.py"]["hint"] == _MISS_HINT
+
+ async def test_change_risk_unknown_ref_keeps_fatal_without_cli_advice(self):
+ result = await get_change_risk(revspec="not-a-ref", repo="backend")
+
+ assert result["error"] == (
+ "Could not read change 'not-a-ref': fatal: ambiguous argument 'not-a-ref': "
+ "unknown revision or path not in the working tree."
+ )
+ assert "Use '--'" not in result["error"]
+ assert "git <command>" not in result["error"]
+
+ @pytest.mark.parametrize("finding_id", ["fix1_x", "fix_future_x", "act_x"])
+ async def test_health_fix_and_action_ids_point_to_fix_id(self, finding_id):
+ result = await get_health(finding_id=finding_id, repo="backend")
+
+ assert result["finding"] is None
+ assert result["resolved"] is False
+ assert result["hint"] == (
+ "Pass fix_first ids (fix1_...) and next_actions ids (act_...) "
+ "as fix_id, not finding_id."
+ )
+
+ async def test_health_plain_finding_miss_stays_hint_free(self):
+ result = await get_health(finding_id="finding_missing", repo="backend")
+
+ assert result["finding"] is None
+ assert result["resolved"] is False
+ assert "hint" not in result
+
+
+ ("raw", "expected"),
+ [
+ ({}, "No grounded answer was found."),
+ ({"note": "No matching evidence."}, "No matching evidence."),
+ ({"answer": " ", "note": "No matching evidence."}, "No matching evidence."),
+ ({"answer": "Existing answer."}, "Existing answer."),
+ ],
+)
+def test_answer_without_error_keeps_its_fallback_and_hint(raw, expected):
+ result = project_answer_payload(raw, question="how does routing work")
+
+ assert result["answer"] == expected
+ assert result["next_action_hint"] == (
+ "Use the first emitted evidence row; refine the question if it does not resolve the issue."
+ )
+
+
+ "target",
+ [
+ "missing.py",
+ "microdot:missing.py",
+ " MICRODOT :missing.py",
+ "missing.py:12",
+ "missing.py:12-20",
+ "missing.py::Symbol",
+ "component:missing",
+ "change:missing",
+ "module:missing",
+ "package:missing",
+ "missing:",
+ "C:/missing.py",
+ "C:missing.py",
+ "/tmp/missing:name.py",
+ ],
+)
+def test_non_alias_misses_keep_the_existing_hint(monkeypatch, target):
+ registry = SimpleNamespace(get_all_aliases=lambda: ["microdot", "tiny"])
+ monkeypatch.setattr(_state, "_registry", registry)
+ response = {"targets": {target: {"unresolved_reason": "no_such_path"}}}
+
+ hint_misses(response, [Route(target, target, "microdot", missed=True)])
+
+ assert response["targets"][target]["hint"] == _MISS_HINT
+
+
[email protected]("target", ["zzz:foo.py", "zzz:foo.py:12-20", "zzz:foo.py::Symbol"])
+def test_unknown_alias_hint_covers_all_response_shapes(monkeypatch, target):
+ registry = SimpleNamespace(get_all_aliases=lambda: ["microdot", "tiny"])
+ monkeypatch.setattr(_state, "_registry", registry)
+ routes = [Route(target, target, "microdot", missed=True)]
+ response = {
+ "targets": {target: {"unresolved_reason": "no_such_path"}},
+ "unresolved": [{"target": target}],
+ }
+ top_level = {"error": "Target not found"}
+
+ hint_misses(response, routes)
+ hint_misses(top_level, routes)
+
+ expected = "Unknown repository alias 'zzz'. Available aliases: microdot, tiny."
+ assert response["targets"][target]["hint"] == expected
+ assert response["unresolved"][0]["hint"] == expected
+ assert top_level["hint"] == expected
+
+
+def test_miss_without_workspace_registry_keeps_existing_hint(monkeypatch):
+ monkeypatch.setattr(_state, "_registry", None)
+ response = {"error": "Target not found"}
+
+ hint_misses(response, [Route("zzz:foo.py", "zzz:foo.py", None, missed=True)])
+
+ assert response["hint"] == _MISS_HINT