Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): forgive get_symbol(id=) and ground a hedged get_answer on the served body (#783)
Raghav Chamadiya3a6000f713ee
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex 662edf99a..faae8780e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -988,6 +988,12 @@ async def get_answer(symbol_bodies: list[dict] = []_seen_bodies: set[tuple[str, str]] = set()+ # True once a tier-0 body (the exact symbol the question named, resolved by+ # symbol anchoring) is inlined. Its full live body IS the ground truth, so a+ # response carrying it is content-grounded even when synthesis hedges — the+ # confidence gate below reads this to avoid the "low, go Read" label that+ # contradicts a payload already holding the answer (2026-07-11 dogfood).+ served_named_body = Falserepo_root = Path(str(ctx.path)) if getattr(ctx, "path", None) else Nonefor _tier, _kind_rank, start, path, s in _body_candidates:if len(symbol_bodies) >= _INLINE_BODY_MAX_SYMBOLS:@@ -1019,6 +1025,8 @@ async def get_answer(entry["continuation"] = f"{path}:{end_served + 1}-{sym_end}"symbol_bodies.append(entry)_seen_bodies.add((path, name))+ if _tier == 0:+ served_named_body = True# Compute confidence from the dominance ratio (top hit vs second hit).# The dominance ratio is a more reliable separator than absolute BM25@@ -1047,7 +1055,14 @@ async def get_answer(# payload (~10k chars) through the conversation cache for no benefit.hedged = _answer_is_hedged(answer_text)if hedged:- confidence = "low"+ # A hedge means the synthesised PROSE is weak — but when the exact+ # symbol the question named is inlined in symbol_bodies (tier-0 anchor,+ # full live body), the answer's ground truth is already in-hand. Labeling+ # that "low" contradicts the payload and fires the "go Read" hint the+ # body makes unnecessary, so the agent bails to Read when it never needed+ # to. Hold such a response at medium; the note below redirects the agent+ # from the hedged prose to the served body.+ confidence = "medium" if served_named_body else "low"# Third gate — identifier-citation gate: when the question explicitly# names identifiers (classes / methods / snake_case / CamelCase) and@@ -1124,7 +1139,7 @@ async def get_answer(payload = {"answer": answer_text,"citations": citations,- "confidence": "low",+ "confidence": confidence,"retrieval_quality": retrieval_quality,"fallback_targets": fallback_targets[:3],"retrieval": [],@@ -1138,10 +1153,22 @@ async def get_answer(# fallback_targets file, which is the whole point of anchoring.if symbol_bodies:payload["symbol_bodies"] = symbol_bodies- payload["note"] = (- "Synthesis hedged, but symbol_bodies carries the live body of "- "the symbol(s) you named — read that to answer."- )+ if served_named_body:+ # The exact symbol the question named is inlined below as live+ # source. That is the answer; the hedge is about the surrounding+ # prose, not the body. Say so, and mark the response grounded so+ # the agent cites the body instead of re-reading the file.+ payload["grounding"] = "symbol_body"+ payload["note"] = (+ "Synthesis hedged on the prose, but symbol_bodies carries "+ "the full live body of the symbol(s) you named — cite that "+ "directly, no verification Read needed."+ )+ else:+ payload["note"] = (+ "Synthesis hedged, but symbol_bodies carries the live body "+ "of the symbol(s) you named — read that to answer."+ )# The hedge often means the rationale isn't in the wiki at all — it's a# code comment. Mine the candidate source for it before sending the# agent off to Read.diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 4e7ad72d4..8d0540303 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -656,10 +656,11 @@ async def _render_ambiguous(@mcp.tool()async def get_symbol(- symbol_id: str,+ symbol_id: str | None = None,context_lines: int = 0,repo: str | None = None,query: str | None = None,+ id: str | None = None,) -> dict:"""Read one function/class/constant with live-verified line bounds.@@ -682,12 +683,23 @@ async def get_symbol(context_lines: extra lines before/after (0-50).repo: usually omitted.query: omission refs only — regex/substring filter on lines.+ id: accepted alias for ``symbol_id`` — the tool table documents this+ tool as ``get_symbol(id)``, so ``id=`` is the natural call and is+ forgiven here rather than met with a hard argument error."""if repo == "all":return _unsupported_repo_all("get_symbol")ctx = await _resolve_repo_context(repo)t0 = time.perf_counter()+ # ``id`` is an alias for ``symbol_id``. The CLAUDE.md tool table and the+ # tool description both refer to this tool as ``get_symbol(id)``, so agents+ # naturally call it with ``id=`` and hit a pydantic "field required" error+ # on ``symbol_id`` — one isError early teaches the agent to abandon the+ # server (agent-context doctrine). Accept both; ``symbol_id`` wins when both+ # are given.+ if not symbol_id and id:+ symbol_id = idif not symbol_id or not symbol_id.strip():return {"symbol_id": symbol_id,diff --git a/tests/unit/server/mcp/test_answer_calibration.py b/tests/unit/server/mcp/test_answer_calibration.pyindex 2952e3b51..5aa6030ad 100644--- a/tests/unit/server/mcp/test_answer_calibration.py+++ b/tests/unit/server/mcp/test_answer_calibration.py@@ -427,6 +427,91 @@ async def test_inline_body_truncation_emits_continuation(setup_mcp, monkeypatch)assert b["continuation"] == "pkg/alpha/one.py:13-60"+# ---------------------------------------------------------------------------+# Hedge + served named-symbol body — a hedge downgrades the PROSE, but when the+# exact symbol the question named is inlined as a live body, the answer's ground+# truth is already served. The response must not read "low, go Read" (which+# contradicts the payload); it holds at medium with grounding="symbol_body".+# ---------------------------------------------------------------------------+++def _patch_anchor(monkeypatch, answer_mod, anchored: dict):+ """Force symbol anchoring to attach ``anchored`` to the top hit, as if the+ question named an indexed symbol whose defining file got promoted."""++ async def _fake_anchor(session, repo_id, question_ids, hits):+ if hits:+ hits[0]["_anchor_symbols"] = [anchored]+ return hits, {"union": {}, "qualified_miss": []}++ monkeypatch.setattr(answer_mod, "_anchor_symbol_hits", _fake_anchor)+++async def test_hedged_but_named_body_served_holds_medium(setup_mcp, monkeypatch, tmp_path):+ """Hedged synthesis + the exact question-named symbol inlined as a live body+ → medium with grounding='symbol_body', not low. The 'low → Read' hint the+ body makes unnecessary must not fire."""+ import repowise.server.mcp_server as mcp_mod+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ (tmp_path / "pkg" / "alpha").mkdir(parents=True)+ (tmp_path / "pkg" / "alpha" / "one.py").write_text(+ "def min_count_policy() -> int:\n"+ " # gate retries at the floor\n"+ " return MIN_COUNT\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))++ _patch_pipeline(monkeypatch, answer_mod, with_symbols=True, symbol=_FN_SYMBOL)+ _patch_anchor(+ monkeypatch,+ answer_mod,+ {+ "name": "min_count_policy",+ "kind": "function",+ "start_line": 1,+ "end_line": 3,+ },+ )+ _patch_provider(+ monkeypatch,+ answer_mod,+ "The provided excerpts do not include the full body of min_count_policy.",+ )++ result = await get_answer("How does min_count_policy work?")+ assert result["confidence"] == "medium"+ assert result["grounding"] == "symbol_body"+ [b] = result["symbol_bodies"]+ assert b["name"] == "min_count_policy"+ assert "return MIN_COUNT" in b["source"]+ assert "cite that directly" in result["note"]+ # The low-confidence "Read the fallback_targets" hint must be gone.+ assert "Low confidence" not in (result["_meta"].get("hint") or "")+++async def test_hedged_without_named_body_stays_low(setup_mcp, monkeypatch):+ """The same hedge, but no anchored body is served → still low (the negative+ control for the grounding bump)."""+ import repowise.server.mcp_server.tool_answer.answer as answer_mod+ from repowise.server.mcp_server import get_answer++ _patch_pipeline(monkeypatch, answer_mod, with_symbols=True, symbol=_FN_SYMBOL)+ _patch_provider(+ monkeypatch,+ answer_mod,+ "The provided excerpts do not include the full body of min_count_policy.",+ )++ result = await get_answer("How does min_count_policy work?")+ assert result["confidence"] == "low"+ assert "grounding" not in result++# ---------------------------------------------------------------------------# Symbol anchoring — force the defining file of a question-named symbol into# the candidate set when fuzzy retrieval missed it.diff --git a/tests/unit/server/mcp/test_symbol_range_and_recovery.py b/tests/unit/server/mcp/test_symbol_range_and_recovery.pyindex 242fd6c11..c20af7fdb 100644--- a/tests/unit/server/mcp/test_symbol_range_and_recovery.py+++ b/tests/unit/server/mcp/test_symbol_range_and_recovery.py@@ -175,3 +175,34 @@ async def test_missing_file_still_errors(setup_mcp, repo_on_disk):result = await get_symbol("pkg/ghost.py::nothing")assert "error" in result+++async def test_id_is_accepted_as_alias_for_symbol_id(setup_mcp, repo_on_disk):+ """The tool table documents this tool as ``get_symbol(id)``, so ``id=`` is+ the natural call. It must resolve exactly like ``symbol_id=`` rather than+ raising a pydantic 'field required' error (a real, recurring footgun that+ teaches the agent to abandon the server)."""+ from repowise.server.mcp_server import get_symbol++ aliased = await get_symbol(id="pkg/mod.py:5-6")+ assert aliased.get("error") is None+ assert aliased["start_line"] == 5+ assert "_DEFAULT_MIN_COUNT = 2" in aliased["source"]+++async def test_symbol_id_wins_when_both_given(setup_mcp, repo_on_disk):+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol("pkg/mod.py:5-6", id="pkg/ghost.py:1-2")+ assert result.get("error") is None+ assert result["start_line"] == 5+++async def test_neither_id_nor_symbol_id_returns_shaped_error(setup_mcp, repo_on_disk):+ from repowise.server.mcp_server import get_symbol++ result = await get_symbol()+ assert "required" in (result.get("error") or "").lower()