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): session-survival hardening for the tool surface (#767)

Raghav Chamadiya890cce93bded
diff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.md
index 393386a9a..0ddee79cf 100644
--- a/docs/MCP_TOOLS.md
+++ b/docs/MCP_TOOLS.md
@@ -217,9 +217,14 @@ Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.
| `context_lines` | int | No | Extra source lines before/after the symbol (0-50, default 0) |
| `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |
-**Returns:** For a symbol id or range: the source bytes (bounded at ~400 lines),
-its exact start/end line numbers, kind, and a `truncated` flag; on a miss, an
-`error` with the closest matches (`fallback_lines` from a live grep). For an
+**Returns:** For a symbol id or range: the source (bounded at ~600 lines,
+each line prefixed with its file line number in the same format as a `Read`
+result), its exact start/end line numbers, kind, and a `truncated` flag; on a
+miss, an `error` with the closest matches (`fallback_lines` from a live grep).
+When several indexed symbols match the id (overloads, re-exports, conditional
+definitions) the response has `ambiguous: true` and a `candidates` list with
+every matching body — none is silently chosen; candidates past the response
+budget appear in `not_rendered` with a `fetch_with` range read. For an
omission ref: the stored content plus provenance (`source`, `created_at`,
`original_tokens`).
diff --git a/packages/core/src/repowise/core/generation/editor_files/tool_table.py b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
index b529b677c..b0c84e8f1 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tool_table.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tool_table.py
@@ -35,9 +35,11 @@ TOOL_TABLE_ROWS: dict[str, tuple[str, str]] = {
"get_symbol": (
"get_symbol(id)",
'One verified body: `"path.py::Name"` (indexed symbol), `"path.py:140-180"` '
- '(live range read), or `"repowise#<hex>"` (omission ref). `verified: true` '
- "means no follow-up Read; `truncated` responses carry a `continuation` naming "
- "the exact next range. Index misses fall back to live-grep `fallback_lines`.",
+ '(live range read), or `"repowise#<hex>"` (omission ref). Source arrives in '
+ "Read's numbered format — treat it as an already-performed Read. `truncated` "
+ "responses carry a `continuation` naming the exact next range; ambiguous ids "
+ "return every match in `candidates`. Index misses fall back to live-grep "
+ "`fallback_lines`.",
),
"search_codebase": (
"search_codebase(query)",
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 0dbf019f5..d87a9faf4 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -30,6 +30,7 @@ from repowise.core.registry import mcp_tool_registry as _mcp_tool_registry
# --- Import submodules in dependency order (triggers tool registration) ---
from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._failure_shield import shield as _failure_shield
from repowise.server.mcp_server._graph_utils import ( # used by routers/graph.py
build_visual_context as _build_visual_context,
)
@@ -65,10 +66,12 @@ from repowise.server.mcp_server.tool_search import search_codebase
from repowise.server.mcp_server.tool_symbol import get_symbol
from repowise.server.mcp_server.tool_why import get_why
-# ``middleware`` wraps each tool with savings instrumentation: every call records
-# the counterfactual raw-exploration tokens its answer replaced into the unified
-# ledger. The wrapper is signature-preserving, so tool schemas are unchanged.
-_mcp_tool_registry.apply(mcp, middleware=_savings_instrument)
+# ``middleware`` wraps each tool twice, both layers signature-preserving so the
+# tool schemas are unchanged. The failure shield sits innermost: no exception
+# may escape to FastMCP as a protocol-level isError (an early isError teaches
+# the agent to abandon the server for the whole session). The savings layer
+# wraps it, so shaped error responses are still dead-end-debited in the ledger.
+_mcp_tool_registry.apply(mcp, middleware=lambda fn: _savings_instrument(_failure_shield(fn)))
# Snapshot the full registered surface so per-server tool selection (single-repo
# vs workspace, config/CLI overrides) can rebuild from it. Selection itself runs
diff --git a/packages/server/src/repowise/server/mcp_server/_failure_shield.py b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
new file mode 100644
index 000000000..0fc84de9b
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
@@ -0,0 +1,105 @@
+"""Failure shield — no recoverable state ever reaches the agent as isError.
+
+One or two protocol-level error results early in a session teach an agent to
+stop calling the server for the rest of that session, so every expected
+condition (repo not indexed, unknown alias, even an unexpected internal crash)
+must come back as a normal success-shaped response that explains what happened
+and what to do next. FastMCP converts any exception that escapes a tool into
+``isError: true``; this wrapper is the last line of defense that keeps that
+from ever happening.
+
+Composed around every tool at registration time (see ``__init__.py``):
+``instrument(shield(fn))`` — the shield sits innermost so the savings layer
+still sees (and dead-end-debits) the shaped error response.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import inspect
+import logging
+from collections.abc import Callable
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# _get_repo raises LookupError with these two message shapes; matching on the
+# message keeps _helpers.py free of any import back-reference to this module.
+_NOT_INDEXED_MARKER = "No repositories found"
+
+
+def _shape_not_indexed() -> dict[str, Any]:
+ """Success-shaped response for a repo that has never been indexed."""
+ return {
+ "error": "This repository has no repowise index yet.",
+ "remedy": (
+ "The user can build one by running 'repowise init' in the repo "
+ "root. Indexing is the user's decision — suggest it once, do not "
+ "run it yourself."
+ ),
+ "guidance": (
+ "Until an index exists, every repowise tool will return this "
+ "notice. Answer questions about this repo with your built-in "
+ "tools (Read/Grep/Glob) for the rest of the session."
+ ),
+ }
+
+
+def _shape_unknown_repo(exc: Exception) -> dict[str, Any]:
+ """Success-shaped response for an unknown repo alias/path/id."""
+ return {
+ "error": str(exc),
+ "remedy": (
+ "Call list_repos to see the valid repo aliases, or omit the "
+ "'repo' argument to use the default repository."
+ ),
+ }
+
+
+def _shape_internal_error(tool: str, exc: Exception) -> dict[str, Any]:
+ """Success-shaped response for an unexpected internal failure."""
+ return {
+ "error": f"{tool} hit an internal error: {type(exc).__name__}: {exc}",
+ "guidance": (
+ "Retry this call once. If it fails again, stop using this tool "
+ "for the rest of the session and mention the error to the user "
+ "— the other repowise tools are unaffected."
+ ),
+ }
+
+
+def _shape_exception(tool: str, exc: Exception) -> dict[str, Any]:
+ if isinstance(exc, LookupError):
+ if _NOT_INDEXED_MARKER in str(exc):
+ return _shape_not_indexed()
+ return _shape_unknown_repo(exc)
+ # Workspace mode raises ValueError("Unknown repo '<alias>'. Available:
+ # [...]") from the registry — same expected condition, different type.
+ if isinstance(exc, ValueError) and str(exc).startswith("Unknown repo"):
+ return _shape_unknown_repo(exc)
+ return _shape_internal_error(tool, exc)
+
+
+def shield(fn: Callable[..., Any]) -> Callable[..., Any]:
+ """Wrap an async MCP tool so no exception escapes to FastMCP.
+
+ Signature-preserving for the same reason as the savings wrapper: FastMCP
+ introspects the wrapped function to build the tool's input schema.
+ """
+ if not inspect.iscoroutinefunction(fn):
+ return fn
+
+ tool = getattr(fn, "__name__", "tool")
+
+ @functools.wraps(fn)
+ async def _wrapped(*args: Any, **kwargs: Any) -> Any:
+ try:
+ return await fn(*args, **kwargs)
+ except Exception as exc:
+ logger.warning("mcp tool %s shielded exception: %s", tool, exc, exc_info=True)
+ return _shape_exception(tool, exc)
+
+ with contextlib.suppress(ValueError, TypeError): # pragma: no cover - exotic callables
+ _wrapped.__signature__ = inspect.signature(fn) # type: ignore[attr-defined]
+ return _wrapped
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 2895b69e5..cb8d23daa 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -416,5 +416,8 @@ def answer_hint(confidence: str, retrieval_count: int) -> str | None:
if confidence == "low":
return "Low confidence — Read the listed fallback_targets to verify before answering."
if retrieval_count == 0:
- return "No wiki hits — fall back to search_codebase or Grep."
+ return (
+ "No wiki hits — try search_codebase (mode=symbol/path) or "
+ "get_context on the named file; Grep only if those miss too."
+ )
return None
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.py
index bd18f1b82..17b13e421 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
@@ -429,8 +429,11 @@ async def get_answer(
"fallback_targets": [],
"retrieval": [],
"note": (
- "No wiki hits for this question. Fall back to "
- "search_codebase or Grep to locate candidate files."
+ "No wiki hits for this question. Rephrase around the code "
+ 'concept, or use search_codebase (mode="symbol" for an '
+ 'identifier, mode="path" for a file name); if the question '
+ "names a file, call get_context on it directly. Grep only "
+ "if those come back empty too."
),
"_meta": _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
@@ -497,7 +500,11 @@ async def get_answer(
f"Read {best_guesses[0]['file']} first — it scored highest "
"but retrieval was ambiguous, so verify before answering."
if best_guesses
- else "Fall back to search_codebase or Grep."
+ else (
+ 'Retry search_codebase with mode="symbol" or '
+ 'mode="path" on the key terms; Grep only if those '
+ "miss too."
+ )
),
"fallback_targets": fallback_targets,
"retrieval": _serialize_hits(hits, limit=_GATED_RETURN_HITS, lean_symbols=True),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index 993f442fe..36d083d2d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -427,19 +427,27 @@ def _result_paths(results: list[dict]) -> list[str]:
def _grep_hint_for(query: str) -> str | None:
- """Build a Grep nudge for identifier-shaped queries, else ``None``."""
+ """Zero-result recovery hint for identifier-shaped queries, else ``None``.
+
+ Only attached when the search produced nothing (see call sites) — a
+ populated result set needs no escape hatch. Points back into the tool
+ surface first; Grep is named only for the one job it genuinely wins:
+ an exhaustive literal sweep of every usage (e.g. before a rename).
+ """
if _looks_like_exact_token(query):
return (
- f"Query {query!r} looks like an exact identifier. Grep will find "
- "literal usages faster and without thematic drift. This tool ran "
- "the search anyway — verify before relying on the results."
+ f"No indexed match for identifier {query!r}. Retry with "
+ 'mode="symbol" (or check spelling/casing); if you need every '
+ "literal usage for an exhaustive sweep such as a rename, Grep "
+ "is the right tool for that."
)
if idents := _embedded_identifiers(query):
shown = ", ".join(repr(t) for t in idents[:3])
return (
- f"Query names identifier(s) {shown} — for their exact "
- "definition/usages, Grep is faster and never drifts "
- "thematically. Semantic results below are concept-level."
+ f"Query names identifier(s) {shown} but nothing matched. Search "
+ 'the identifier alone with mode="symbol", then pipe the hit '
+ "into get_symbol for its body. For an exhaustive every-usage "
+ "sweep, Grep the literal name."
)
return None
@@ -600,7 +608,7 @@ async def search_codebase(
# kind is filtered per-repo inside _search_single_repo, before each
# repo's limit cut, so the fused list is already kind-pure and full.
federated = await _federated_search(query, limit, page_type, kind)
- if grep_hint:
+ if grep_hint and not federated.get("results"):
federated["grep_hint"] = grep_hint
return federated
@@ -663,6 +671,6 @@ async def search_codebase(
"results": output,
"_meta": _build_meta(repository=repository, targets=_result_paths(output)),
}
- if grep_hint:
+ if grep_hint and not output:
response["grep_hint"] = grep_hint
return response
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index ed94230c9..d3ff5e8c4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -90,6 +90,14 @@ _MAX_RANGE_LINES = 200
# but the file exists on disk.
_MAX_FALLBACK_MATCHES = 8
+# When a lookup is ambiguous (overloads, re-exports, conditional defs) every
+# candidate body is served in ONE response — a silently-picked wrong candidate
+# sends the agent into a read-spiral that costs far more than the extra bytes.
+# This caps the total candidate-source chars; the first candidate always
+# renders, the rest render while budget remains and are otherwise listed with
+# an exact range read that fetches them.
+_AMBIGUITY_CHAR_BUDGET = 20_000
+
def _extract_omission_ref(symbol_id: str) -> str | None:
"""Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""
@@ -223,7 +231,7 @@ async def _resolve_range_read(
"start_line": s,
"end_line": e,
"total_lines": total,
- "source": source,
+ "source": _number_lines(source, s),
"truncated": range_truncated,
"verified": True,
"_meta": _build_meta(
@@ -267,7 +275,7 @@ def _live_grep_fallback(repo_root: Path, file_path: str, name: str) -> list[dict
for i, line in enumerate(lines, 1):
if bare in line:
lo, hi = max(1, i - 2), min(len(lines), i + 2)
- matches.append({"line": i, "context": "\n".join(lines[lo - 1 : hi])})
+ matches.append({"line": i, "context": _number_lines("\n".join(lines[lo - 1 : hi]), lo)})
if len(matches) >= _MAX_FALLBACK_MATCHES:
break
return matches
@@ -353,49 +361,46 @@ def _bare_name(name: str) -> str:
return tail
-def _pick_canonical(rows: list[WikiSymbol], queried_file_path: str | None) -> WikiSymbol | None:
- """Deterministically select one row from a candidate list.
+def _order_candidates(rows: list[WikiSymbol], queried_file_path: str | None) -> list[WikiSymbol]:
+ """Deterministically order a candidate list, best match first.
- Priority:
+ Priority for the head slot:
1. file_path matches the file_path embedded in the queried symbol_id
2. deterministic tiebreak on the (id) primary key (ascending)
+
+ Ambiguous lookups (len > 1) are NOT collapsed here — get_symbol serves
+ every candidate so the agent, not a heuristic, decides which one it
+ meant. The remainder is ordered by source position for readability.
"""
- if not rows:
- return None
- if len(rows) == 1:
- return rows[0]
- if queried_file_path:
- matching = [r for r in rows if r.file_path == queried_file_path]
- if matching:
- rows = matching
- # Deterministic: lowest id wins. (No confidence column today; leaving
- # room to add one without changing the fallback.)
- rows_sorted = sorted(rows, key=lambda r: r.id or "")
- if len(rows) > 1:
- _log.warning(
- "get_symbol: %d duplicate rows for lookup (file=%s); picked id=%s",
- len(rows),
- queried_file_path,
- rows_sorted[0].id,
- )
- return rows_sorted[0]
+ if len(rows) <= 1:
+ return rows
+
+ def _head_key(r: WikiSymbol) -> tuple:
+ file_match = 0 if (queried_file_path and r.file_path == queried_file_path) else 1
+ return (file_match, r.id or "")
+
+ head = min(rows, key=_head_key)
+ rest = sorted(
+ (r for r in rows if r is not head),
+ key=lambda r: (r.file_path or "", r.start_line or 0, r.id or ""),
+ )
+ return [head, *rest]
-async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> WikiSymbol | None:
- """Look up a symbol by id, qualified_name, or bare name. None if absent.
+async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> list[WikiSymbol]:
+ """Look up a symbol by id, qualified_name, or bare name.
+
+ Returns every row the first matching lookup stage produced, best match
+ first (see :func:`_order_candidates`); ``[]`` when nothing matched.
+ A multi-row result means the id is genuinely ambiguous — overloads,
+ re-exports, conditional defs — and the caller serves ALL of them rather
+ than guessing (a wrong silent pick triggers a read-spiral).
Language-agnostic: the qualified-name portion of the symbol_id is
normalized across ``.``, ``::`` and ``/`` separators before matching,
so callers can pass any of ``Class.method``, ``Class::method``, or
``Class/method`` and still resolve. Only the name part is normalized —
file paths are never rewritten.
-
- Duplicate-safe: every query uses ``.all()`` + :func:`_pick_canonical`
- instead of ``.scalar_one_or_none()``. The canonical constraint
- ``uq_wiki_symbol`` on ``(repository_id, symbol_id)`` already prevents
- duplicates on the primary key, but the fallback lookups on
- ``(file_path, qualified_name)`` and ``(file_path, name)`` can legitimately
- return several rows (e.g. overloads, re-exports, conditional defs).
"""
file_path, _name = _parse_symbol_id(symbol_id)
variants = _symbol_id_variants(symbol_id)
@@ -408,13 +413,12 @@ async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> WikiSymbol |
)
)
rows = list(res.scalars().all())
- picked = _pick_canonical(rows, file_path)
- if picked is not None:
- return picked
+ if rows:
+ return _order_candidates(rows, file_path)
_, name = _parse_symbol_id(symbol_id)
if not name:
- return None
+ return []
name_variants = _name_variants(name)
@@ -428,9 +432,8 @@ async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> WikiSymbol |
)
)
rows = list(res.scalars().all())
- picked = _pick_canonical(rows, file_path)
- if picked is not None:
- return picked
+ if rows:
+ return _order_candidates(rows, file_path)
# 3. Match on (file_path, name) — last segment of qualified name.
bare = _bare_name(name)
@@ -442,11 +445,10 @@ async def _resolve_symbol(session, repo_id: str, symbol_id: str) -> WikiSymbol |
)
)
rows = list(res.scalars().all())
- picked = _pick_canonical(rows, file_path)
- if picked is not None:
- return picked
+ if rows:
+ return _order_candidates(rows, file_path)
- return None
+ return []
def _read_file_text(repo_path: Path, file_path: str) -> str | None:
@@ -496,6 +498,106 @@ def _slice_text(
return "\n".join(lines[s - 1 : e]), s, e, total
+def _number_lines(source: str, start_line: int) -> str:
+ """Prefix each line with its 1-based file line number, Read-style.
+
+ Byte-parity with the agent's own Read tool output (``cat -n`` format:
+ right-aligned number, tab, line). Source served in the exact shape of an
+ already-performed Read is treated as one — the agent edits from it
+ instead of re-Reading the file to "see the real format".
+ """
+ return "\n".join(f"{n:>6}\t{line}" for n, line in enumerate(source.splitlines(), start_line))
+
+
+async def _render_ambiguous(
+ rows: list[WikiSymbol],
+ symbol_id: str,
+ ctx: Any,
+ repository: Any,
+ t0: float,
+ context_lines: int,
+) -> dict:
+ """Serve EVERY candidate body for an ambiguous symbol id in one response.
+
+ A deterministic-but-wrong pick reads as authoritative and sends the agent
+ editing the wrong overload; returning all candidates costs bytes once and
+ removes the guess. The first candidate always renders; the rest render
+ while the char budget lasts and are otherwise listed with the exact range
+ read that fetches them.
+ """
+ repo_root = Path(str(ctx.path))
+ text_cache: dict[str, str | None] = {}
+ candidates: list[dict] = []
+ not_rendered: list[dict] = []
+ remaining = _AMBIGUITY_CHAR_BUDGET
+
+ for i, row in enumerate(rows):
+ if row.file_path not in text_cache:
+ text_cache[row.file_path] = _read_file_text(repo_root, row.file_path)
+ text = text_cache[row.file_path]
+
+ entry: dict[str, Any] = {
+ "symbol_id": row.symbol_id,
+ "file": row.file_path,
+ "name": row.name,
+ "kind": row.kind,
+ "qualified_name": row.qualified_name,
+ "signature": row.signature,
+ }
+ if text is None:
+ entry["note"] = "source file could not be read"
+ not_rendered.append(entry)
+ continue
+
+ check = check_symbol_bounds(row, text)
+ if check.corrected:
+ await heal_symbol_row(ctx.session_factory, row, check.start_line, check.end_line)
+ source, start, end, _total = _slice_text(
+ text, check.start_line, check.end_line, context_lines
+ )
+ entry.update({"start_line": start, "end_line": end, "verified": check.verified})
+
+ numbered = _number_lines(source, start)
+ if i > 0 and len(numbered) > remaining:
+ entry["fetch_with"] = f"{row.file_path}:{start}-{end}"
+ not_rendered.append(entry)
+ continue
+ remaining -= len(numbered)
+ entry["source"] = numbered
+ candidates.append(entry)
+
+ response: dict[str, Any] = {
+ "symbol_id": symbol_id,
+ "ambiguous": True,
+ "match_count": len(rows),
+ "candidates": candidates,
+ "note": (
+ f"{len(rows)} symbols match this id (overloads, re-exports, or "
+ "conditional definitions). All candidate bodies are included — "
+ "none was silently chosen; pick by signature and line range."
+ ),
+ "_meta": _build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ repository=repository,
+ targets=sorted({r.file_path for r in rows}),
+ ),
+ }
+ if not_rendered:
+ response["not_rendered"] = not_rendered
+ response["note"] += (
+ " Candidates over the response budget are listed in not_rendered —"
+ " fetch one via get_symbol with its fetch_with range."
+ )
+
+ from repowise.core.distill.budget import estimate_tokens
+ from repowise.server.mcp_server._savings import declare_replaced
+
+ full_tokens = sum(estimate_tokens(t) for t in text_cache.values() if t)
+ if full_tokens:
+ declare_replaced(response, full_tokens)
+ return response
+
+
@mcp.tool()
async def get_symbol(
symbol_id: str,
@@ -506,14 +608,17 @@ async def get_symbol(
"""Read one function/class/constant with live-verified line bounds.
Raw source of one indexed symbol, bounded (~600 lines) — cheaper than
- Read+offset math. ``verified: true`` = bounds checked (or corrected)
- against the live file: no follow-up Read needed. ``bounds:
- "approximate"`` = the symbol moved and re-location failed. Also serves
- live range reads ("path.py:140-180", ≤200 lines, always verified) and
- omission refs ("repowise#<12-hex>"). Index misses grep the live file
- and return fallback_lines instead of a dead end. When ``truncated`` is
- true the response carries a ``continuation`` token — the exact range read
- that fetches the remainder; pass it straight back to get_symbol.
+ Read+offset math. ``source`` uses Read's exact line-numbered format;
+ treat it as an already-performed Read. ``verified: true`` = bounds
+ checked (or corrected) against the live file: no follow-up Read needed.
+ ``bounds: "approximate"`` = the symbol moved and re-location failed.
+ An ambiguous id (overloads, re-exports) returns ALL matching bodies in
+ ``candidates`` — none is silently chosen. Also serves live range reads
+ ("path.py:140-180", ≤200 lines, always verified) and omission refs
+ ("repowise#<12-hex>"). Index misses grep the live file and return
+ fallback_lines instead of a dead end. When ``truncated`` is true the
+ response carries a ``continuation`` token — the exact range read that
+ fetches the remainder; pass it straight back to get_symbol.
Args:
symbol_id: "path/to/file.py::Name" (from get_context),
@@ -560,14 +665,15 @@ async def get_symbol(
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- row = await _resolve_symbol(session, repository.id, symbol_id)
+ rows = await _resolve_symbol(session, repository.id, symbol_id)
exclude_spec = _get_exclude_spec(ctx.path)
- if row is None or is_excluded(getattr(row, "file_path", None), exclude_spec):
+ rows = [r for r in rows if not is_excluded(r.file_path, exclude_spec)]
+ if not rows:
# Dead-end recovery: constants/imports/aliases between indexed
# symbols miss the index but live in the file — grep the live file
# for the name and serve the matching lines instead of a pure error.
- if row is None and ctx.path:
+ if ctx.path:
file_part, name_part = _parse_symbol_id(symbol_id)
if file_part and name_part and not is_excluded(file_part, exclude_spec):
matches = _live_grep_fallback(Path(str(ctx.path)), file_part, name_part)
@@ -613,6 +719,10 @@ async def get_symbol(
),
}
+ if len(rows) > 1:
+ return await _render_ambiguous(rows, symbol_id, ctx, repository, t0, context_lines)
+
+ row = rows[0]
repo_root = Path(str(ctx.path))
text = _read_file_text(repo_root, row.file_path)
@@ -663,7 +773,7 @@ async def get_symbol(
"end_line": end,
"symbol_start_line": check.start_line,
"symbol_end_line": check.end_line,
- "source": source,
+ "source": _number_lines(source, start),
"truncated": truncated,
"verified": check.verified,
"_meta": _build_meta(
diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.py
index ca6dd6cf9..fd297f174 100644
--- a/tests/unit/server/mcp/test_budget.py
+++ b/tests/unit/server/mcp/test_budget.py
@@ -273,7 +273,8 @@ async def test_get_symbol_unknown_ref_errors(setup_mcp, repo_root: Path):
@pytest.mark.asyncio
async def test_get_symbol_normal_path_byte_identical(setup_mcp, repo_root: Path):
- """A real symbol_id must still slice the exact on-disk byte range."""
+ """A real symbol_id slices the exact on-disk byte range, served in
+ Read's numbered format (line content verbatim after the number+tab)."""
import repowise.server.mcp_server as mcp_mod
from repowise.server.mcp_server import get_symbol
@@ -285,7 +286,7 @@ async def test_get_symbol_normal_path_byte_identical(setup_mcp, repo_root: Path)
# WikiSymbol fixture rows: login spans lines 20..40 (see conftest).
result = await get_symbol("src/auth/service.py::login")
- assert result["source"] == "\n".join(lines[19:40])
+ assert result["source"] == "\n".join(f"{n:>6}\t{lines[n - 1]}" for n in range(20, 41))
assert result["start_line"] == 20 and result["end_line"] == 40
assert result["truncated"] is False
diff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.py
new file mode 100644
index 000000000..533ed1c7c
--- /dev/null
+++ b/tests/unit/server/mcp/test_failure_shield.py
@@ -0,0 +1,121 @@
+"""No recoverable state may reach the agent as a protocol-level isError.
+
+An early isError teaches an agent to abandon the MCP server for the whole
+session, so the failure shield must convert every exception that escapes a
+tool handler — including the un-init'd-repo LookupError that previously fired
+on EVERY tool's first call — into a success-shaped dict with a remedy.
+"""
+
+from __future__ import annotations
+
+import inspect
+
+import pytest
+
+from repowise.server.mcp_server._failure_shield import shield
+
+
+async def empty_mcp(factory, fts, vector_store):
+ """MCP globals wired to an EMPTY database — the un-init'd repo state."""
+ import repowise.server.mcp_server as mcp_mod
+
+ mcp_mod._session_factory = factory
+ mcp_mod._fts = fts
+ mcp_mod._vector_store = vector_store
+ mcp_mod._repo_path = "/tmp/test-repo"
+ yield
+ mcp_mod._session_factory = None
+ mcp_mod._fts = None
+ mcp_mod._vector_store = None
+ mcp_mod._repo_path = None
+
+
+async def test_uninitialized_repo_is_success_shaped(empty_mcp):
+ """The 'No repositories found' LookupError becomes guidance, not isError."""
+ from repowise.server.mcp_server import get_symbol
+
+ result = await shield(get_symbol)("pkg/mod.py::alpha")
+
+ assert isinstance(result, dict) # no exception escaped
+ assert "no repowise index" in result["error"].lower()
+ assert "repowise init" in result["remedy"]
+ # The user decides whether to index; the agent must not run init itself.
+ assert "user" in result["remedy"]
+ # Session-scoped guidance: use built-in tools instead of retrying forever.
+ assert "Read/Grep/Glob" in result["guidance"]
+
+
+async def test_unknown_repo_alias_is_success_shaped(setup_mcp):
+ from repowise.server.mcp_server import get_symbol
+
+ result = await shield(get_symbol)("pkg/mod.py::alpha", repo="no-such-repo")
+
+ assert "no-such-repo" in result["error"]
+ assert "list_repos" in result["remedy"]
+
+
+async def test_workspace_unknown_repo_valueerror_is_success_shaped():
+ """Workspace mode raises ValueError (not LookupError) for a bad alias —
+ caught live on a real workspace server before this branch existed."""
+
+ async def workspace_tool(repo: str) -> dict:
+ raise ValueError(f"Unknown repo {repo!r}. Available: ['a', 'b']")
+
+ result = await shield(workspace_tool)("no-such-repo")
+
+ assert "no-such-repo" in result["error"]
+ assert "list_repos" in result["remedy"]
+ assert "Retry" not in result.get("guidance", "")
+
+
+async def test_unexpected_exception_is_success_shaped():
+ async def exploding_tool(x: int) -> dict:
+ raise RuntimeError("boom")
+
+ result = await shield(exploding_tool)(1)
+
+ assert "RuntimeError" in result["error"]
+ assert "exploding_tool" in result["error"]
+ assert "Retry this call once" in result["guidance"]
+
+
+async def test_successful_result_passes_through_untouched():
+ async def fine_tool() -> dict:
+ return {"answer": 42}
+
+ assert await shield(fine_tool)() == {"answer": 42}
+
+
+def test_shield_preserves_signature_for_fastmcp_schema():
+ async def tool_fn(symbol_id: str, context_lines: int = 0) -> dict:
+ return {}
+
+ wrapped = shield(tool_fn)
+ assert wrapped.__name__ == "tool_fn"
+ assert str(inspect.signature(wrapped)) == str(inspect.signature(tool_fn))
+
+
+def test_sync_callables_pass_through():
+ def sync_fn() -> dict:
+ return {}
+
+ assert shield(sync_fn) is sync_fn
+
+
+def test_server_composes_shield_into_middleware():
+ """Pin the __init__.py wiring: every registered tool goes through the
+ shield. Without this, a refactor could silently drop the composition and
+ reopen the isError-on-every-tool hole."""
+ import inspect as _inspect
+
+ import repowise.server.mcp_server as mcp_mod
+
+ source = _inspect.getsource(mcp_mod)
+ assert "_failure_shield" in source
+ assert "_savings_instrument(_failure_shield(fn))" in source
diff --git a/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py b/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py
new file mode 100644
index 000000000..7d31890bf
--- /dev/null
+++ b/tests/unit/server/mcp/test_symbol_ambiguity_and_format.py
@@ -0,0 +1,171 @@
+"""Ambiguous symbol ids serve ALL candidates; raw source is Read-format.
+
+* A lookup matching several rows (overloads, re-exports, conditional defs)
+ returns every candidate body in one response — a deterministic-but-wrong
+ silent pick reads as authoritative and sends the agent editing the wrong
+ overload.
+* Served source lines carry Read's exact ``cat -n`` numbering so the agent
+ treats the response as an already-performed Read.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.mcp_server.tool_symbol import _number_lines
+
+DUP_SOURCE = """try:
+ def dup(x):
+ return 1
+except NameError:
+ def dup(x):
+ return 2
+"""
+
+MODULE_SOURCE = '''"""A module."""
+
+import os
+
+_DEFAULT_MIN_COUNT = 2
+MAX_RETRIES = 5
+
+
+def alpha(x):
+ return x + 1
+'''
+
+
+def repo_on_disk(tmp_path, monkeypatch):
+ import repowise.server.mcp_server as mcp_mod
+
+ (tmp_path / "pkg").mkdir()
+ (tmp_path / "pkg" / "dup.py").write_text(DUP_SOURCE)
+ (tmp_path / "pkg" / "mod.py").write_text(MODULE_SOURCE)
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+ return tmp_path
+
+
+async def _add_dup_rows(session):
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository, WikiSymbol
+
+ repo = (await session.execute(select(Repository))).scalars().first()
+ for sid, start, end, marker in (("dup1", 2, 3, "aaaa"), ("dup2", 5, 6, "bbbb")):
+ session.add(
+ WikiSymbol(
+ id=marker + sid,
+ repository_id=repo.id,
+ file_path="pkg/dup.py",
+ symbol_id=f"pkg/dup.py::dup#{sid[-1]}",
+ name="dup",
+ qualified_name="dup",
+ kind="function",
+ signature="def dup(x)",
+ start_line=start,
+ end_line=end,
+ language="python",
+ )
+ )
+ await session.flush()
+
+
+def test_number_lines_matches_read_format():
+ # cat -n: right-aligned width-6 line number, tab, verbatim line.
+ assert _number_lines("a\nb", 5) == " 5\ta\n 6\tb"
+ assert _number_lines("x", 1234567) == "1234567\tx"
+
+
+async def test_ambiguous_symbol_returns_all_candidates(setup_mcp, repo_on_disk, session):
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_dup_rows(session)
+ result = await get_symbol("pkg/dup.py::dup")
+
+ assert result.get("error") is None
+ assert result["ambiguous"] is True
+ assert result["match_count"] == 2
+ assert len(result["candidates"]) == 2
+ assert "none was silently chosen" in result["note"]
+
+ # Every candidate carries its own verified body, and the two bodies
+ # differ — the whole point is letting the agent pick by content.
+ first, second = result["candidates"]
+ assert "return 1" in first["source"]
+ assert "return 2" in second["source"]
+ assert first["verified"] is True
+ assert second["verified"] is True
+ # Deterministic head slot: lowest id ("aaaa...") leads.
+ assert first["start_line"] == 2
+
+
+async def test_unambiguous_lookup_is_unchanged_shape(setup_mcp, repo_on_disk, session):
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository, WikiSymbol
+ from repowise.server.mcp_server import get_symbol
+
+ repo = (await session.execute(select(Repository))).scalars().first()
+ session.add(
+ WikiSymbol(
+ id="alpha1",
+ repository_id=repo.id,
+ file_path="pkg/mod.py",
+ symbol_id="pkg/mod.py::alpha",
+ name="alpha",
+ qualified_name="alpha",
+ kind="function",
+ signature="def alpha(x)",
+ start_line=9,
+ end_line=10,
+ language="python",
+ )
+ )
+ await session.flush()
+
+ result = await get_symbol("pkg/mod.py::alpha")
+ assert "ambiguous" not in result
+ assert result["verified"] is True
+ # Read-format parity: each served line is "<n>\t<code>" with real numbers.
+ assert " 9\tdef alpha(x):" in result["source"]
+ assert " 10\t return x + 1" in result["source"]
+
+
+async def test_range_read_source_is_numbered(setup_mcp, repo_on_disk):
+ from repowise.server.mcp_server import get_symbol
+
+ result = await get_symbol("pkg/mod.py:5-6")
+ assert result["source"] == " 5\t_DEFAULT_MIN_COUNT = 2\n 6\tMAX_RETRIES = 5"
+
+
+async def test_fallback_lines_are_numbered(setup_mcp, repo_on_disk):
+ from repowise.server.mcp_server import get_symbol
+
+ result = await get_symbol("pkg/mod.py::MAX_RETRIES")
+ assert result.get("resolution") == "live_grep"
+ [match] = [m for m in result["fallback_lines"] if m["line"] == 6]
+ assert " 6\tMAX_RETRIES = 5" in match["context"]
+
+
+async def test_budget_overflow_lists_unrendered_with_fetch_range(
+ setup_mcp, repo_on_disk, session, monkeypatch
+):
+ import repowise.server.mcp_server.tool_symbol as ts
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_dup_rows(session)
+ # Force the sub-budget below the second candidate's size: it must be
+ # listed (never dropped) with the exact range read that fetches it.
+ monkeypatch.setattr(ts, "_AMBIGUITY_CHAR_BUDGET", 10)
+
+ result = await get_symbol("pkg/dup.py::dup")
+ assert len(result["candidates"]) == 1 # the first always renders
+ [skipped] = result["not_rendered"]
+ assert skipped["fetch_with"] == "pkg/dup.py:5-6"
+ assert "not_rendered" in result["note"]
diff --git a/tests/unit/server/test_tool_symbol.py b/tests/unit/server/test_tool_symbol.py
index 6a9c1cbe6..e1e30ec04 100644
--- a/tests/unit/server/test_tool_symbol.py
+++ b/tests/unit/server/test_tool_symbol.py
@@ -16,7 +16,7 @@ from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import WikiSymbol, _new_uuid
from repowise.server.mcp_server.tool_symbol import (
_name_variants,
- _pick_canonical,
+ _order_candidates,
_resolve_symbol,
_symbol_id_variants,
)
@@ -70,36 +70,35 @@ def test_symbol_id_variants_preserves_file_path() -> None:
@pytest.mark.asyncio
-async def test_resolve_symbol_dot_and_colon_forms_equivalent(
- client, app, session_factory
-) -> None:
+async def test_resolve_symbol_dot_and_colon_forms_equivalent(client, app, session_factory) -> None:
repo = await create_test_repo(client)
await _add(session_factory, repo["id"]) # stored with "::" form
async with get_session(session_factory) as session:
- row_colon = await _resolve_symbol(
+ rows_colon = await _resolve_symbol(
session,
repo["id"],
"src/flask/sansio/app.py::App::update_template_context",
)
- row_dot = await _resolve_symbol(
+ rows_dot = await _resolve_symbol(
session,
repo["id"],
"src/flask/sansio/app.py::App.update_template_context",
)
- assert row_colon is not None
- assert row_dot is not None
- assert row_colon.id == row_dot.id
- assert row_dot.name == "update_template_context"
+ assert len(rows_colon) == 1
+ assert len(rows_dot) == 1
+ assert rows_colon[0].id == rows_dot[0].id
+ assert rows_dot[0].name == "update_template_context"
@pytest.mark.asyncio
-async def test_resolve_symbol_duplicate_rows_picks_canonical(
+async def test_resolve_symbol_duplicate_rows_returns_all_canonical_first(
client, app, session_factory
) -> None:
"""When the (file_path, qualified_name) lookup returns several rows,
- we must return one canonical row instead of raising MultipleResultsFound.
+ ALL of them come back (get_symbol serves every candidate) with the
+ deterministic canonical pick first — and no MultipleResultsFound.
"""
repo = await create_test_repo(client)
# Two rows share the same (file_path, qualified_name, name) — simulates
@@ -124,45 +123,46 @@ async def test_resolve_symbol_duplicate_rows_picks_canonical(
)
async with get_session(session_factory) as session:
- row = await _resolve_symbol(
+ rows = await _resolve_symbol(
session,
repo["id"],
"src/flask/sansio/blueprints.py::BlueprintSetupState.add_url_rule",
)
- assert row is not None
- # Deterministic tiebreak: lowest id wins.
- assert row.id.startswith("aaaa")
- assert row.file_path == "src/flask/sansio/blueprints.py"
+ # Both candidates surface — the ambiguity is the agent's to resolve.
+ assert len(rows) == 2
+ # Deterministic tiebreak for the head slot: lowest id wins.
+ assert rows[0].id.startswith("aaaa")
+ assert {r.file_path for r in rows} == {"src/flask/sansio/blueprints.py"}
@pytest.mark.asyncio
-async def test_resolve_symbol_nonexistent_returns_none(
- client, app, session_factory
-) -> None:
+async def test_resolve_symbol_nonexistent_returns_none(client, app, session_factory) -> None:
repo = await create_test_repo(client)
await _add(session_factory, repo["id"])
async with get_session(session_factory) as session:
- row = await _resolve_symbol(
+ rows = await _resolve_symbol(
session,
repo["id"],
"src/flask/sansio/app.py::App.this_method_does_not_exist",
)
- assert row is None
+ assert rows == []
-def test_pick_canonical_prefers_matching_file_path() -> None:
+def test_order_candidates_prefers_matching_file_path() -> None:
class Fake:
def __init__(self, id_: str, path: str) -> None:
self.id = id_
self.file_path = path
+ self.start_line = 1
- rows = [Fake("zzzz", "other/path.py"), Fake("aaaa", "src/target.py")]
- picked = _pick_canonical(rows, "src/target.py") # type: ignore[arg-type]
- assert picked.id == "aaaa" # type: ignore[union-attr]
+ rows = [Fake("aaaa", "other/path.py"), Fake("zzzz", "src/target.py")]
+ ordered = _order_candidates(rows, "src/target.py") # type: ignore[arg-type]
+ # File match beats lower id for the head slot; nothing is dropped.
+ assert [r.id for r in ordered] == ["zzzz", "aaaa"]
- # No file_path hint: fall back to lowest id.
- picked = _pick_canonical(rows, None) # type: ignore[arg-type]
- assert picked.id == "aaaa" # type: ignore[union-attr]
+ # No file_path hint: lowest id leads.
+ ordered = _order_candidates(rows, None) # type: ignore[arg-type]
+ assert [r.id for r in ordered] == ["aaaa", "zzzz"]