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
fix(mcp): name the right selector or include when get_health or get_risk drops an argument (#4366)
Raghav Chamadiyafbee1f776c59
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex e865ca1c8..a532cdbd5 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -342,7 +342,7 @@ Code-health scores and findings from stored analysis, across defect risk, mainta| `counts` | string | `"everything"` | `code_shape` drops the git-derived half of the score || `repo` | string | default repo | `"all"` not supported |-- Pass one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id`; two return `mode: "conflict"`.+- Pass one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id`; two return `mode: "conflict"`. A miss on an id minted for another selector (a `fix1_` id passed as `plan_id`) carries a `hint` naming the right one.- `fix_first` shows five items unless `limit` comes with `only=["fix_first"]`, which pages up to 25.- The response is bounded: pair `include` with `only` to keep one block, e.g. `get_health(include=["refactoring"], only=["refactoring_opportunities"])`.diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 2cc45a070..0f7d29fc4 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -113,6 +113,7 @@ A value outside a closed vocabulary is dropped, so the response is the one you w| `get_answer` | `include` | `_meta.ignored_arguments` map: `{"include": [...]}` || `get_health` | `refactoring_*`, `performance_*`, `scope`, `counts` | Top-level map, e.g. `{"counts": "code-shape"}` |+- **`get_risk`:** `include` values `tests` and `blast` without `changed_files` land in one entry with `"requires": "changed_files"`, since only PR mode builds them.- **`search_codebase`:** an unknown `mode` runs as `auto`; a `pattern` entry carries `"superseded_by": "query"`.- **`get_health`:** a value meant for the other control (`scope="code_shape"`) adds `ignored_arguments_hint`, except on a detail lookup. A misspelled `only` key lands in `unknown_only_keys`; a detail lookup (`finding_id`, `plan_id`, `opportunity_id`) lists `scope` and `counts` there too, since they cannot act on one row.@@ -651,7 +652,7 @@ One ranked queue across refactoring, performance and code-shape work, the same o- **`untested_complexity`:** estimated tiers only with `include=["unverified"]`; never both measures.- **`doc_drift`:** evidence to check, not a proven defect.- **`what_if`:** `ceiling` is the score with no structure deduction (history's cap shrinking with it); `target_out_of_reach` when below 8.0; `fix_all_structure` gains, top 3 `findings`, and `top_fixes` across files. Each fix has `points` (upper bound when its category is capped) and `gain` (`file`, `average`, `hotspot`). `structure_deduction` may include withheld types no fix covers.-- **`only` aliases:** `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names land in `unknown_only_keys` with `unknown_only_keys_hint`; for targeted `signals`, name `metrics`.+- **`only` aliases:** `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names land in `unknown_only_keys` with `unknown_only_keys_hint`, which names the `include` a missing include-gated key needs; for targeted `signals`, name `metrics`.### Refactoringdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.pyindex d99e338f8..82677332d 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@@ -32,6 +32,9 @@ from repowise.server.mcp_server.tool_health.serialize import (from repowise.server.services.performance_health import PerformanceHealthServicefrom repowise.server.services.refactoring_health import RefactoringHealthService+#: Prefix of the Do next action ids ``get_overview``'s ``next_actions`` hands out.+_ACTION_ID_PREFIX = "act_"+async def _detail_response(session: Any,@@ -85,6 +88,42 @@ async def _detail_response(return None+#: Id prefixes as minted (fix_first/model.py, finding_identity.py,+#: refactoring/identity.py and opportunity.py, perf/causal.py), each with the+#: selector that resolves it. Ordered so ``refac`` never shadows ``refop``.+_SELECTOR_OF_PREFIX: tuple[tuple[str, str, str], ...] = (+ ("fix", "fix_id", "fix_first ids (fix1_...)"),+ (_ACTION_ID_PREFIX, "fix_id", f"next_actions ids ({_ACTION_ID_PREFIX}...)"),+ ("finding_", "finding_id", "finding ids (finding_...)"),+ (+ _REFACTORING_OPPORTUNITY_PREFIX,+ "opportunity_id",+ f"refactoring opportunity ids ({_REFACTORING_OPPORTUNITY_PREFIX}...)",+ ),+ ("refac", "plan_id", "refactoring plan ids (refac...)"),+ ("perf", "opportunity_id", "performance opportunity ids (perf...)"),+)+++def _wrong_selector_hint(passed: str, value: str) -> str | None:+ """Name the selector *value*'s prefix belongs to, when it is not *passed*."""+ for prefix, selector, label in _SELECTOR_OF_PREFIX:+ if value.startswith(prefix):+ return f"Pass {label} as {selector}, not {passed}." if selector != passed else None+ return None+++def _hint_wrong_selector(result: dict[str, Any], **selectors: str | None) -> None:+ """On a miss, name the selector the id was minted for. Never resolved under+ that selector instead: the caller swapped an argument, and answering anyway+ would hide it."""+ if result.get("found") or result.get("resolved"):+ return+ for name, value in selectors.items():+ if value and (hint := _wrong_selector_hint(name, value)):+ result["hint"] = hint++async def _lower_priority(session: Any, repository_id: str, finding: Any) -> str | None:"""The finding's tier reason, measured over its file's open findings asthe list measured it: file-held rows included, as the list reads them."""@@ -118,18 +157,10 @@ 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-#: Prefix of the Do next action ids ``get_overview``'s ``next_actions`` hands out.-_ACTION_ID_PREFIX = "act_"-_FIX_NOT_FOUND = ("get_health() lists the current fix_first ids (fix1_...); ""get_overview() lists the next_actions ids (act_...)"diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/projection.py b/packages/server/src/repowise/server/mcp_server/tool_health/projection.pyindex 9e227b518..ce8e973f4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/projection.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/projection.py@@ -40,6 +40,22 @@ _UNKNOWN_ONLY_HINT = ("performance is an `include` value. See docs/agent/MCP_TOOLS.md.")+#: Keys built only when ``include`` asks (blocks.py, pillars.py): a missing+#: include, not a misspelling, is why such a key is absent.+_INCLUDE_OF_KEY = {+ **dict.fromkeys(("performance_opportunities", "performance_summary"), "performance"),+ **dict.fromkeys(+ (+ "refactoring_opportunities",+ "refactoring_summary",+ "refactoring_plans",+ "suggestion_legend",+ ),+ "refactoring",+ ),+ **{k: k for k in ("trend", "coverage", "doc_drift", "untested_complexity", "what_if")},+}+#: Which control accepts each value, to name the right one for a swapped value._CONTROL_OF_VALUE = {**dict.fromkeys(COUNTS, "counts"), **dict.fromkeys(SCOPES, "scope")}@@ -132,5 +148,17 @@ def _project(if unknown:result["unknown_only_keys"] = unknown_stamp_collection(result, "unknown_only_keys", total=len(unknown))- result["unknown_only_keys_hint"] = _UNKNOWN_ONLY_HINT+ result["unknown_only_keys_hint"] = _unknown_only_hint(req, unknown)return result+++def _unknown_only_hint(req: HealthRequest, unknown: list[str]) -> str:+ """The generic hint, led by the include each include-gated miss needs."""+ needs = [+ f'only=["{raw}"] needs include=["{include}"].'+ for raw, resolved in zip(req.only, req.only_list, strict=True)+ if raw in unknown+ and (include := _INCLUDE_OF_KEY.get(resolved))+ and include not in req.include_set+ ]+ return " ".join(dict.fromkeys([*needs, _UNKNOWN_ONLY_HINT]))diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.pyindex cbc5f9e39..a940546bc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py@@ -50,6 +50,7 @@ from repowise.server.mcp_server.tool_health.blocks import add_optional_blocksfrom repowise.server.mcp_server.tool_health.dashboard import build_dashboardfrom repowise.server.mcp_server.tool_health.details import (_detail_response,+ _hint_wrong_selector,_note_inapplicable_controls,_selector_conflict,)@@ -247,6 +248,13 @@ async def get_health(recipe="recipe" in req.include_set,)if detail is not None:+ _hint_wrong_selector(+ detail,+ fix_id=fix_id,+ finding_id=finding_id,+ plan_id=plan_id,+ opportunity_id=opportunity_id,+ )_attach_semantics(detail, req)return _note_inapplicable_controls(detail, scope, counts)data = await load_health_data(diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 9defe47e5..2cb957be6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -111,6 +111,16 @@ _BLAST_INCLUDES: dict[str, tuple[str, ...]] = {"graph": ("direct_risks",)}#: ``blast`` the ``pr_blast_radius`` dossier, ``changes`` each file's recent#: Change Records._INCLUDE_BLOCKS = frozenset(_TARGET_CARD_INCLUDES) | {"blast", "scales", "tests", "changes"}+#: Blocks only the PR directive builds: without ``changed_files`` they hold nothing.+_PR_ONLY_INCLUDES = ("tests", "blast")+++def _name_pr_only_includes(ignored: list[dict], include: set[str]) -> None:+ """Name the PR-only blocks a targets-only call asked for, so their absence+ is not read as "no tests" or "no blast radius"."""+ unused = [block for block in _PR_ONLY_INCLUDES if block in include]+ if unused:+ ignored.append({"argument": "include", "values": unused, "requires": "changed_files"})def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:@@ -557,6 +567,8 @@ async def get_risk()_drop_opt_in_blocks(response, include_set)drop_echoed_target(response.get("targets"))+ if not changed_files:+ _name_pr_only_includes(ignored, include_set)attach_ignored_arguments(response, ignored)collector.attach(response)return responsediff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 9b07bdc4e..d999f4818 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -1908,6 +1908,37 @@ async def test_unknown_only_keys_are_rejected_with_a_hint(setup_mcp, health_dataassert "performance_opportunities" in result["unknown_only_keys_hint"]+async def test_unknown_only_key_names_the_include_it_needs(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health(only=["performance_opportunities", "refactoring", "trnd"])+ hint = result["unknown_only_keys_hint"]+ assert hint.startswith(+ 'only=["performance_opportunities"] needs include=["performance"]. '+ 'only=["refactoring"] needs include=["refactoring"]. '+ )+ assert "trnd" not in hint+++def test_unknown_only_hint_skips_an_include_already_passed():+ from repowise.server.mcp_server.tool_health.projection import (+ _UNKNOWN_ONLY_HINT,+ _unknown_only_hint,+ )+ from repowise.server.mcp_server.tool_health.request import HealthRequest++ req = HealthRequest(+ targets=None, include=["performance"], only=["performance_opportunities"], repo=None,+ limit=None, cursor=0, refactoring_view="diversified", refactoring_type=None,+ refactoring_confidence=None, refactoring_effort=None, refactoring_scope=None,+ performance_view=None, performance_context=None, performance_boundary=None,+ performance_confidence=None, performance_actionability=None, performance_sort=None,+ scope="all", counts="everything",+ )+ assert _unknown_only_hint(req, ["performance_opportunities"]) == _UNKNOWN_ONLY_HINT++@pytest.mark.asyncioasync def test_only_projection_keeps_unresolved(setup_mcp, health_data):"""A typo'd target stays named however the response is projected.diff --git a/tests/unit/server/mcp/test_workspace_error_guidance.py b/tests/unit/server/mcp/test_workspace_error_guidance.pyindex 961d3a6eb..0b974ceb1 100644--- a/tests/unit/server/mcp/test_workspace_error_guidance.py+++ b/tests/unit/server/mcp/test_workspace_error_guidance.py@@ -75,17 +75,86 @@ class TestWorkspaceErrors: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):+ @pytest.mark.parametrize(+ ("finding_id", "label"),+ [+ ("fix1_x", "fix_first ids (fix1_...)"),+ ("fix_future_x", "fix_first ids (fix1_...)"),+ ("act_x", "next_actions ids (act_...)"),+ ],+ )+ async def test_health_fix_and_action_ids_point_to_fix_id(self, finding_id, label):result = await get_health(finding_id=finding_id, repo="backend")assert result["finding"] is Noneassert result["resolved"] is False- assert result["hint"] == (- "Pass fix_first ids (fix1_...) and next_actions ids (act_...) "- "as fix_id, not finding_id."+ assert result["hint"] == f"Pass {label} as fix_id, not finding_id."++ @pytest.mark.parametrize(+ ("selector", "value", "hint"),+ [+ (+ "plan_id",+ "fix1_8b581db6e7f864b2979e",+ "Pass fix_first ids (fix1_...) as fix_id, not plan_id.",+ ),+ (+ "plan_id",+ "perf3_8b581db6e7f864b2979e",+ "Pass performance opportunity ids (perf...) as opportunity_id, not plan_id.",+ ),+ (+ "fix_id",+ "finding_8b581db6e7f864b2979e",+ "Pass finding ids (finding_...) as finding_id, not fix_id.",+ ),+ (+ "opportunity_id",+ "refac4_8b581db6e7f864b2979e",+ "Pass refactoring plan ids (refac...) as plan_id, not opportunity_id.",+ ),+ (+ "plan_id",+ "refop4_8b581db6e7f864b2979e",+ "Pass refactoring opportunity ids (refop...) as opportunity_id, not plan_id.",+ ),+ ],+ )+ async def test_health_wrong_kind_id_names_its_selector(self, selector, value, hint):+ result = await get_health(**{selector: value}, repo="backend")++ assert result["hint"] == hint++ @pytest.mark.parametrize(+ ("selector", "value"),+ [+ ("plan_id", "refac4_8b581db6e7f864b2979e"),+ ("fix_id", "fix1_8b581db6e7f864b2979e"),+ ("opportunity_id", "perf3_8b581db6e7f864b2979e"),+ ("plan_id", "not-an-id"),+ ],+ )+ async def test_health_right_kind_miss_stays_hint_free(self, selector, value):+ result = await get_health(**{selector: value}, repo="backend")++ assert "hint" not in result++ async def test_risk_names_pr_only_includes_without_changed_files(self):+ result = await get_risk(+ targets=["src/probe.py"], include=["tests", "blast", "owners"], repo="backend")+ assert result["ignored_arguments"] == [+ {"argument": "include", "values": ["tests", "blast"], "requires": "changed_files"}+ ]++ async def test_risk_pr_mode_keeps_tests_include(self):+ result = await get_risk(+ changed_files=["src/probe.py"], include=["tests"], repo="backend"+ )++ assert "ignored_arguments" not in result+async def test_health_plain_finding_miss_stays_hint_free(self):result = await get_health(finding_id="finding_missing", repo="backend")@@ -168,3 +237,29 @@ def test_miss_without_workspace_registry_keeps_existing_hint(monkeypatch):hint_misses(response, [Route("zzz:foo.py", "zzz:foo.py", None, missed=True)])assert response["hint"] == _MISS_HINT+++def test_every_minted_id_prefix_maps_to_its_own_selector():+ """Guards the prefix table against an id format changing where it is minted."""+ from repowise.core.analysis.health.finding_identity import finding_public_id+ from repowise.core.analysis.health.fix_first.model import fix_id+ from repowise.core.analysis.health.perf.causal import stable_id as perf_id+ from repowise.core.analysis.health.refactoring.identity import stable_id as plan_id+ from repowise.core.analysis.health.refactoring.opportunity import opportunity_public_id+ from repowise.server.mcp_server.tool_health.details import _wrong_selector_hint++ finding = SimpleNamespace(+ biomarker_type="complexity", function_name=None, details_json=None,+ line_start=1, line_end=2, dimension="defect", file_path="a.py",+ )+ minted = {+ "fix_id": [fix_id("finding", "x"), "act_x"],+ "finding_id": [finding_public_id(finding)],+ "plan_id": [plan_id(("k",))],+ "opportunity_id": [perf_id(("k",)), opportunity_public_id(["p"], "a.py")],+ }+ for selector, ids in minted.items():+ for value in ids:+ assert _wrong_selector_hint(selector, value) is None, value+ other = "plan_id" if selector != "plan_id" else "fix_id"+ assert f"as {selector}, not {other}." in (_wrong_selector_hint(other, value) or "")