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): exclude_patterns filtering for context, answer, and federated search (PR 4b) (#340)

joptimus8f9fc1ba5837
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 9332e985c..1ca3a3c4a 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
@@ -56,9 +56,12 @@ from repowise.server.mcp_server._answer_pipeline import (
)
from repowise.server.mcp_server._answer_pipeline import hydrate_hits as _hydrate_hits
from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
_get_repo,
_resolve_repo_context,
_unsupported_repo_all,
+ filter_dicts_by_key,
+ is_excluded,
)
from repowise.server.mcp_server._meta import answer_hint as _answer_hint
from repowise.server.mcp_server._meta import build_meta as _build_meta
@@ -121,6 +124,7 @@ async def get_answer(
t0 = time.perf_counter()
ctx = await _resolve_repo_context(repo)
+ exclude_spec = _get_exclude_spec(ctx.path)
if not question or not question.strip():
return {
@@ -165,6 +169,16 @@ async def get_answer(
# promotion, source-body excerpts). Give synthesis another shot
# with the new context rather than pinning the bad answer.
hedged_cache = _answer_is_hedged(payload.get("answer", ""))
+ # A row cached before exclude_patterns changed may reference a
+ # now-excluded file — in its fields or its prose. Re-synthesize
+ # rather than scrub the fields and leave the prose dangling.
+ cached_paths = [
+ *(payload.get("citations") or []),
+ *(payload.get("fallback_targets") or []),
+ *(h.get("target_path") for h in (payload.get("retrieval") or [])),
+ *(g.get("file") for g in (payload.get("best_guesses") or [])),
+ ]
+ excluded_cache = any(is_excluded(p, exclude_spec) for p in cached_paths)
if schema_stale:
_log.info(
"Bypassing cache entry at schema v%s (current v%s)",
@@ -173,6 +187,8 @@ async def get_answer(
)
elif hedged_cache:
_log.info("Bypassing hedged cache entry for re-synthesis")
+ elif excluded_cache:
+ _log.info("Bypassing cache entry referencing a now-excluded path")
else:
payload["_meta"] = _build_meta(
timing_ms=(time.perf_counter() - t0) * 1000,
@@ -194,6 +210,10 @@ async def get_answer(
hits = await _hybrid_retrieve(question, ctx)
hits = await _hydrate_hits(hits, ctx, scope=scope)
+ # Drop excluded files right after hydration (which attaches target_path) so
+ # they never enter ranking, citations, or fallback_targets.
+ hits = filter_dicts_by_key(hits, "target_path", exclude_spec)
+
# Term-coverage re-rank before any graph-aware bias so conjunctive
# matches survive the merge.
hits = _rerank_by_coverage(hits, question)
@@ -215,6 +235,9 @@ async def get_answer(
# damped score, then re-sorts.
with contextlib.suppress(Exception):
hits = await _expand_via_graph(hits, ctx)
+ # Re-filter: graph expansion can pull excluded neighbors back in (before the
+ # cap, so an excluded neighbor can't occupy a top-5 slot).
+ hits = filter_dicts_by_key(hits, "target_path", exclude_spec)
# Always cap retrieval hits at 5 for the response payload.
hits = hits[:5]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index cd8965c90..bb81b0b45 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -30,6 +30,7 @@ from repowise.core.persistence.database import get_session
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._helpers import (
+ _get_exclude_spec,
_get_repo,
_resolve_repo_context,
_unsupported_repo_all,
@@ -88,6 +89,8 @@ async def get_context(
# must pass include explicitly.
include_set = set(include) if include else {"docs", "freshness"}
+ exclude_spec = _get_exclude_spec(ctx.path)
+
import time as _time
_t0 = _time.perf_counter()
@@ -102,6 +105,7 @@ async def get_context(
t,
include_set,
compact,
+ exclude_spec=exclude_spec,
)
for t in targets
]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index cf22f2f72..7d1155a86 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -30,6 +30,7 @@ from repowise.core.persistence.models import (
HealthFinding,
Repository,
)
+from repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path_list
# Minimum confidence for call edges to filter false positives
_MIN_CALL_CONFIDENCE = 0.7
@@ -44,6 +45,7 @@ async def _resolve_call_graph(
*,
want_callers: bool = False,
want_callees: bool = False,
+ exclude_spec: Any = None,
) -> None:
"""Resolve callers/callees for a symbol and attach to result_data."""
repo_id = repository.id
@@ -129,6 +131,9 @@ async def _resolve_call_graph(
else:
callees.append(entry)
+ callers = filter_dicts_by_key(callers, "file", exclude_spec)
+ callees = filter_dicts_by_key(callees, "file", exclude_spec)
+
# Sort by confidence DESC
callers.sort(key=lambda x: -(x.get("confidence") or 0))
callees.sort(key=lambda x: -(x.get("confidence") or 0))
@@ -187,6 +192,8 @@ async def _resolve_community(
repository: Repository,
target: str,
result_data: dict[str, Any],
+ *,
+ exclude_spec: Any = None,
) -> None:
"""Resolve community membership and attach to result_data["community"]."""
repo_id = repository.id
@@ -206,7 +213,7 @@ async def _resolve_community(
# Get top members (cap at 10 for compact output)
members = await get_community_members(session, repo_id, node.community_id, limit=10)
- member_paths = [m.node_id for m in members]
+ member_paths = filter_path_list([m.node_id for m in members], exclude_spec)
# Neighboring communities (cap at 5)
cross_edges = await get_cross_community_edges(session, repo_id, node.community_id)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index 10153d353..be70eda8a 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -25,6 +25,11 @@ from repowise.core.persistence.models import (
Repository,
WikiSymbol,
)
+from repowise.server.mcp_server._helpers import (
+ filter_dicts_by_key,
+ filter_path_list,
+ is_excluded,
+)
from repowise.server.mcp_server.tool_context.enrichment import (
_resolve_call_graph,
_resolve_community,
@@ -66,11 +71,22 @@ async def _resolve_one_target(
target: str,
include: set[str] | None,
compact: bool = False,
+ *,
+ exclude_spec: Any = None,
) -> dict:
"""Resolve a single target and return its full context."""
repo_id = repository.id
result_data: dict[str, Any] = {}
+ # Reject excluded file / ``path::Name`` targets outright (bare symbol names
+ # aren't path-matchable here and fall through to neighbor filtering).
+ gate_path = target.split("::", 1)[0] if "::" in target else target
+ if is_excluded(gate_path, exclude_spec):
+ return {
+ "target": target,
+ "error": f"'{target}' is excluded by exclude_patterns configuration",
+ }
+
# --- Determine target type ---
# 1. Try file page (most common)
page_id = f"file_page:{target}"
@@ -215,6 +231,7 @@ async def _resolve_one_target(
.limit(5)
)
suggestions = [row[0] for row in res.all() if row[0] != target]
+ suggestions = filter_path_list(suggestions, exclude_spec)
if suggestions:
return {
"target": target,
@@ -317,7 +334,9 @@ async def _resolve_one_target(
)
)
importers = res.scalars().all()
- docs["imported_by"] = [e.source_node_id for e in importers]
+ docs["imported_by"] = filter_path_list(
+ [e.source_node_id for e in importers], exclude_spec
+ )
# Community info (compact=False only, ~80 bytes)
res = await session.execute(
@@ -352,14 +371,18 @@ async def _resolve_one_target(
)
)
file_pages = res.scalars().all()
- docs["files"] = [
- {
- "path": f.target_path,
- "description": f.title,
- "confidence_score": f.confidence,
- }
- for f in file_pages
- ]
+ docs["files"] = filter_dicts_by_key(
+ [
+ {
+ "path": f.target_path,
+ "description": f.title,
+ "confidence_score": f.confidence,
+ }
+ for f in file_pages
+ ],
+ "path",
+ exclude_spec,
+ )
elif target_type == "symbol":
sym = sym_matches[0] # type: ignore[possibly-undefined]
@@ -384,13 +407,17 @@ async def _resolve_one_target(
)
)
edges = res.scalars().all()
- docs["used_by"] = [e.source_node_id for e in edges][:20]
+ docs["used_by"] = filter_path_list([e.source_node_id for e in edges], exclude_spec)[:20]
# Candidates
if len(sym_matches) > 1: # type: ignore[possibly-undefined]
- docs["candidates"] = [
- {"name": m.name, "kind": m.kind, "file_path": m.file_path}
- for m in sym_matches[1:5] # type: ignore[possibly-undefined]
- ]
+ docs["candidates"] = filter_dicts_by_key(
+ [
+ {"name": m.name, "kind": m.kind, "file_path": m.file_path}
+ for m in sym_matches[1:5] # type: ignore[possibly-undefined]
+ ],
+ "file_path",
+ exclude_spec,
+ )
result_data["docs"] = docs
@@ -616,6 +643,7 @@ async def _resolve_one_target(
result_data,
want_callers=want_callers,
want_callees=want_callees,
+ exclude_spec=exclude_spec,
)
# --- Metrics (replaces get_graph_metrics) ---
@@ -624,7 +652,9 @@ async def _resolve_one_target(
# --- Community (replaces get_community) ---
if include and "community" in include:
- await _resolve_community(session, repository, target, result_data)
+ await _resolve_community(
+ session, repository, target, result_data, exclude_spec=exclude_spec
+ )
# --- Code health (Phase 2) ---
if include and "health" in include:
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 b6ed5a1d4..d37136790 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -112,7 +112,22 @@ async def _search_single_repo(
"relevance_score": r.score,
})
- return output[:limit], method
+ output = output[:limit]
+
+ # Attach target_path and drop excluded hits per repo (so federated search
+ # honours each repo's own exclude_patterns) before aggregation.
+ if output:
+ page_ids = [item["page_id"] for item in output]
+ async with get_session(ctx.session_factory) as session:
+ res = await session.execute(
+ select(Page.id, Page.target_path).where(Page.id.in_(page_ids))
+ )
+ page_info = {row[0]: row[1] for row in res.all()}
+ for item in output:
+ item["target_path"] = page_info.get(item["page_id"], "")
+ output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))
+
+ return output, method
async def _federated_search(query: str, limit: int, page_type: str | None) -> dict:
diff --git a/tests/unit/server/mcp/test_mcp_exclude_filter_context_answer.py b/tests/unit/server/mcp/test_mcp_exclude_filter_context_answer.py
new file mode 100644
index 000000000..ac3d131cf
--- /dev/null
+++ b/tests/unit/server/mcp/test_mcp_exclude_filter_context_answer.py
@@ -0,0 +1,262 @@
+"""Exclude-pattern filtering for the custom-logic MCP surfaces (PR 4b).
+
+Covers the three pipelines that PR 4a left untouched because filtering has to
+happen *inside* their assembly/retrieval/aggregation steps, not at a single
+result-list chokepoint:
+
+ * ``get_context`` — target gate + neighbor/related-file filtering
+ * ``get_answer`` — retrieval-hit filtering before synthesis/citations
+ * ``search`` (federated) — per-repo filtering before RRF aggregation
+"""
+
+from __future__ import annotations
+
+import json as _json
+
+import pathspec
+import pytest
+
+SPEC = pathspec.PathSpec.from_lines("gitwildmatch", ["src/auth/middleware.py", "src/db/"])
+
+
+# ---------------------------------------------------------------------------
+# Surface 1: get_context enrichment
+# ---------------------------------------------------------------------------
+
+
+async def test_get_context_gates_excluded_file_target(setup_mcp, monkeypatch):
+ """A requested file target that is excluded returns an error, not a card."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["src/db/models.py"], include=["docs"], compact=False)
+ t = result["targets"]["src/db/models.py"]
+ assert "error" in t
+ assert "exclude" in t["error"].lower()
+
+
+async def test_get_context_gates_excluded_symbol_id_target(setup_mcp, monkeypatch):
+ """A ``path::Name`` target whose file is excluded is gated too."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["src/db/models.py::User"], include=["docs"])
+ t = result["targets"]["src/db/models.py::User"]
+ assert "error" in t
+
+
+async def test_get_context_filters_excluded_imported_by(setup_mcp, monkeypatch):
+ """An excluded importer must not appear in a non-excluded file's imported_by."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ # src/auth/middleware.py imports src/auth/service.py (edge ge2).
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["src/auth/service.py"], include=["docs"], compact=False)
+ t = result["targets"]["src/auth/service.py"]
+ assert "src/auth/middleware.py" not in t["docs"]["imported_by"]
+
+
+async def test_get_context_imported_by_unfiltered_without_spec(setup_mcp, monkeypatch):
+ """Sanity: with no exclude spec the importer is still present."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: None)
+
+ result = await get_context(["src/auth/service.py"], include=["docs"], compact=False)
+ t = result["targets"]["src/auth/service.py"]
+ assert "src/auth/middleware.py" in t["docs"]["imported_by"]
+
+
+async def test_get_context_suggestions_drop_excluded_files(setup_mcp, monkeypatch):
+ """Fuzzy not-found suggestions must not surface excluded files."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ # "models.py" resolves to no page/symbol; fuzzy match finds src/db/models.py.
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["models.py"], include=["docs"])
+ t = result["targets"]["models.py"]
+ assert "error" in t
+ assert "src/db/models.py" not in t.get("suggestions", [])
+
+
+async def test_get_context_suggestions_present_without_spec(setup_mcp, monkeypatch):
+ """Control: without a spec the fuzzy suggestion is still offered."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: None)
+
+ result = await get_context(["models.py"], include=["docs"])
+ t = result["targets"]["models.py"]
+ assert "src/db/models.py" in t.get("suggestions", [])
+
+
+async def test_get_context_filters_excluded_community_member(setup_mcp, monkeypatch):
+ """Excluded community co-members must not leak into the community block."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ # service.py and middleware.py share community 1; middleware is excluded.
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["src/auth/service.py"], include=["community"])
+ community = result["targets"]["src/auth/service.py"]["community"]
+ assert community is not None
+ assert "src/auth/middleware.py" not in community["top_members"]
+ assert "src/auth/service.py" in community["top_members"]
+
+
+async def test_get_context_filters_excluded_module_child_files(setup_mcp, monkeypatch):
+ """Module child-file listings drop excluded files."""
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_context(["src/auth"], include=["docs"], compact=False)
+ files = result["targets"]["src/auth"]["docs"]["files"]
+ paths = [f["path"] for f in files]
+ assert "src/auth/middleware.py" not in paths
+ assert "src/auth/service.py" in paths
+
+
+# ---------------------------------------------------------------------------
+# Surface 2: get_answer retrieval + citations
+# ---------------------------------------------------------------------------
+
+
+async def test_get_answer_filters_excluded_hits(setup_mcp, monkeypatch):
+ """Excluded files never become fallback_targets / retrieval / citations."""
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ async def _fake_retrieve(question, ctx):
+ return [
+ {"page_id": "file_page:src/auth/service.py", "score": 5.0},
+ {"page_id": "file_page:src/db/models.py", "score": 4.0},
+ ]
+
+ async def _fake_hydrate(hits, ctx, *, scope=None):
+ mapping = {
+ "file_page:src/auth/service.py": "src/auth/service.py",
+ "file_page:src/db/models.py": "src/db/models.py",
+ }
+ for h in hits:
+ h["target_path"] = mapping[h["page_id"]]
+ h["title"] = h["target_path"]
+ h["summary"] = ""
+ h["snippet"] = ""
+ return hits
+
+ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)
+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)
+ monkeypatch.setattr(answer_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_answer("how does the db layer work")
+
+ assert "src/db/models.py" not in result.get("fallback_targets", [])
+ retrieved_paths = [h.get("target_path") for h in result.get("retrieval", [])]
+ assert "src/db/models.py" not in retrieved_paths
+ best = [g.get("file") for g in result.get("best_guesses", [])]
+ assert "src/db/models.py" not in best
+ # The non-excluded hit survives.
+ assert "src/auth/service.py" in result.get("fallback_targets", [])
+
+
+async def test_get_answer_bypasses_cache_with_excluded_path(setup_mcp, monkeypatch):
+ """A cached payload citing a now-excluded file is bypassed, not returned."""
+ import repowise.server.mcp_server as mcp_mod
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.core.persistence.models import AnswerCache
+ from repowise.server.mcp_server import get_answer
+ from repowise.server.mcp_server.tool_answer.config import _ANSWER_SCHEMA_VERSION
+ from repowise.server.mcp_server.tool_answer.synthesis import _hash_question
+
+ question = "how does the db layer work"
+ async with mcp_mod._session_factory() as s:
+ s.add(
+ AnswerCache(
+ id="ac_excluded",
+ repository_id="repo1",
+ question_hash=_hash_question(question),
+ question=question,
+ payload_json=_json.dumps(
+ {
+ "_schema_version": _ANSWER_SCHEMA_VERSION,
+ "answer": "CACHED ANSWER about src/db/models.py",
+ "citations": ["src/db/models.py"],
+ "fallback_targets": ["src/db/models.py"],
+ "confidence": "high",
+ }
+ ),
+ )
+ )
+ await s.commit()
+
+ # Empty retrieval keeps the bypassed path deterministic (no LLM call).
+ async def _empty_retrieve(question, ctx):
+ return []
+
+ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _empty_retrieve)
+ monkeypatch.setattr(answer_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ result = await get_answer(question)
+
+ # Cache was bypassed (not the stored answer) and the excluded path is gone.
+ assert result.get("answer") != "CACHED ANSWER about src/db/models.py"
+ assert "src/db/models.py" not in result.get("citations", [])
+ assert "src/db/models.py" not in result.get("fallback_targets", [])
+
+
+# ---------------------------------------------------------------------------
+# Surface 3: federated ("all repos") search
+# ---------------------------------------------------------------------------
+
+
+async def test_search_single_repo_attaches_and_filters_target_path(setup_mcp, monkeypatch):
+ """_search_single_repo attaches target_path and honours the repo's spec."""
+ import repowise.server.mcp_server as mcp_mod
+ import repowise.server.mcp_server.tool_search as search_mod
+ from repowise.server.mcp_server._helpers import _resolve_repo_context
+ from repowise.server.mcp_server.tool_search import _search_single_repo
+
+ await mcp_mod._vector_store.embed_and_upsert(
+ "file_page:src/auth/service.py",
+ "Auth Service — Main authentication service class",
+ {"title": "Auth Service", "page_type": "file_page", "target_path": "src/auth/service.py"},
+ )
+ await mcp_mod._vector_store.embed_and_upsert(
+ "file_page:src/db/models.py",
+ "DB Models — SQLAlchemy ORM models",
+ {"title": "DB Models", "page_type": "file_page", "target_path": "src/db/models.py"},
+ )
+
+ monkeypatch.setattr(search_mod, "_get_exclude_spec", lambda _p: SPEC)
+
+ ctx = await _resolve_repo_context(None)
+ results, _method = await _search_single_repo(ctx, "models service", limit=10, page_type=None)
+
+ paths = [r.get("target_path") for r in results]
+ assert paths, "expected at least one hit"
+ assert all(p is not None for p in paths), "every federated hit must carry target_path"
+ assert "src/db/models.py" not in paths