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): filter exclude_patterns from MCP tool responses (#339)
joptimus1fd50a5a6638
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex a2de96d3a..4dee2e33c 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -420,3 +420,71 @@ def _compute_alignment("stale_count": len(stale),"sibling_coverage": round(sibling_coverage, 2) if sibling_coverage is not None else None,}+++# ---------------------------------------------------------------------------+# Per-repo exclude_patterns filtering (issue 5 of #296)+#+# Excluded files are skipped at ingest time, but rows may predate an+# exclude_patterns change, so MCP tools filter their results at query time too.+# ---------------------------------------------------------------------------+++def _get_exclude_spec(repo_path: "Path | str") -> "Any":+ """Compile the repo's ``exclude_patterns`` into a PathSpec, or None."""+ import pathspec++ from repowise.core.repo_config import load_repo_config++ patterns = load_repo_config(repo_path).get("exclude_patterns") or []+ if not patterns:+ return None+ return pathspec.PathSpec.from_lines("gitwildmatch", patterns)+++def is_excluded(path: "str | None", spec: "Any") -> bool:+ """True if *path* matches *spec* (None spec or path -> not excluded)."""+ return bool(spec is not None and path and spec.match_file(path))+++def filter_rows_by_attr(rows: list, attr: str, spec: "Any") -> list:+ """Shape A: drop ORM rows whose ``attr`` path is excluded."""+ if not spec:+ return rows+ return [r for r in rows if not is_excluded(getattr(r, attr, None), spec)]+++def filter_graph_nodes(nodes: list, spec: "Any") -> list:+ """Shape B: file nodes match on ``node_id``, symbol nodes on ``file_path``."""+ if not spec:+ return nodes+ out = []+ for n in nodes:+ path = n.node_id if getattr(n, "node_type", None) == "file" else n.file_path+ if is_excluded(path, spec):+ continue+ out.append(n)+ return out+++def filter_dicts_by_key(items: list, key: str, spec: "Any") -> list:+ """Shape C: drop result dicts whose ``key`` path is excluded."""+ if not spec:+ return items+ return [d for d in items if not is_excluded(d.get(key), spec)]+++def filter_path_list(paths: "list | None", spec: "Any") -> list:+ """Shape D: filter a list of path strings (None -> [])."""+ if not paths:+ return []+ if not spec:+ return list(paths)+ return [p for p in paths if not is_excluded(p, spec)]+++def filter_embedded_path_ids(ids: list, spec: "Any") -> list:+ """Shape E: ids look like ``"path::Name"``; match on the file portion."""+ if not spec:+ return ids+ return [i for i in ids if not is_excluded(i.split("::", 1)[0], spec)]diff --git a/packages/server/src/repowise/server/mcp_server/tool_annotate.py b/packages/server/src/repowise/server/mcp_server/tool_annotate.pyindex 654063527..383035813 100644--- a/packages/server/src/repowise/server/mcp_server/tool_annotate.py+++ b/packages/server/src/repowise/server/mcp_server/tool_annotate.py@@ -11,9 +11,11 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ is_excluded,)from repowise.core.registry import mcp_tool_registry as mcp@@ -38,6 +40,8 @@ async def annotate_file(if repo == "all":return _unsupported_repo_all("annotate_file")ctx = await _resolve_repo_context(repo)+ if is_excluded(target, _get_exclude_spec(ctx.path)):+ return {"target": target, "error": f"'{target}' is excluded by exclude_patterns."}from repowise.core.persistence.models import Pagediff --git a/packages/server/src/repowise/server/mcp_server/tool_callers.py b/packages/server/src/repowise/server/mcp_server/tool_callers.pyindex c069af927..eb5e47054 100644--- a/packages/server/src/repowise/server/mcp_server/tool_callers.py+++ b/packages/server/src/repowise/server/mcp_server/tool_callers.py@@ -26,9 +26,12 @@ from repowise.core.persistence.crud import (from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNodefrom 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 build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -132,8 +135,10 @@ async def get_callers_callees(repo_id = repository.id# Resolve symbol+ exclude_spec = _get_exclude_spec(ctx.path)node = await _resolve_symbol_node(session, repo_id, symbol_id)- if node is None:+ node_path = node.node_id if node and node.node_type == "file" else getattr(node, "file_path", None)+ if node is None or is_excluded(node_path, exclude_spec):return {"symbol_id": symbol_id,"error": (@@ -193,6 +198,10 @@ async def get_callers_callees(else:callees.append(entry)+ # Drop callers/callees that live in excluded files.+ callers = filter_dicts_by_key(callers, "file", exclude_spec)+ callees = filter_dicts_by_key(callees, "file", exclude_spec)+# Sort by confidence DESC, then by namecallers.sort(key=lambda x: (-x.get("confidence", 0), x.get("name", "")))callees.sort(key=lambda x: (-x.get("confidence", 0), x.get("name", "")))diff --git a/packages/server/src/repowise/server/mcp_server/tool_community.py b/packages/server/src/repowise/server/mcp_server/tool_community.pyindex 6b713b733..baa6ecd9e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_community.py+++ b/packages/server/src/repowise/server/mcp_server/tool_community.py@@ -19,9 +19,11 @@ from repowise.core.persistence.crud import (from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNodefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ filter_graph_nodes,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -102,8 +104,13 @@ async def get_community(members_list: list[dict[str, Any]] = []member_count = 0if include_members:- members = await get_community_members(- session, repo_id, community_id, limit=member_limit+ members = filter_graph_nodes(+ list(+ await get_community_members(+ session, repo_id, community_id, limit=member_limit+ )+ ),+ _get_exclude_spec(ctx.path),)member_count = len(members)for m in members:diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex 709cc00ee..35009e548 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -14,10 +14,12 @@ from repowise.core.persistence.models import ()from repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_is_workspace_mode,_resolve_all_contexts,_resolve_repo_context,+ filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -113,7 +115,9 @@ async def get_dead_code(DeadCodeFinding.status == "open",)all_result = await session.execute(all_query)- repo_findings = list(all_result.scalars().all())+ repo_findings = filter_rows_by_attr(+ list(all_result.scalars().all()), "file_path", _get_exclude_spec(ctx.path)+ )finding_paths = list({f.file_path for f in repo_findings})git_meta_map: dict[str, Any] = {}diff --git a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py b/packages/server/src/repowise/server/mcp_server/tool_decision_records.pyindex 3a9c83bba..9b06ffabc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py+++ b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py@@ -9,17 +9,25 @@ from repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import DecisionRecordfrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ filter_path_list,+ is_excluded,)from repowise.core.registry import mcp_tool_registry as mcp_VALID_ACTIONS = frozenset({"create", "update", "update_status", "delete", "list", "get"})-def _serialize_decision(rec: DecisionRecord) -> dict[str, Any]:- """Convert a DecisionRecord ORM object to a plain dict."""+def _serialize_decision(rec: DecisionRecord, spec: Any = None) -> dict[str, Any]:+ """Convert a DecisionRecord ORM object to a plain dict.++ When *spec* is given, affected_files / evidence_file pointing at excluded+ files are dropped so excluded paths never surface in query results.+ """+ evidence_file = None if is_excluded(rec.evidence_file, spec) else rec.evidence_filereturn {"id": rec.id,"repository_id": rec.repository_id,@@ -30,11 +38,11 @@ def _serialize_decision(rec: DecisionRecord) -> dict[str, Any]:"rationale": rec.rationale,"alternatives": json.loads(rec.alternatives_json),"consequences": json.loads(rec.consequences_json),- "affected_files": json.loads(rec.affected_files_json),+ "affected_files": filter_path_list(json.loads(rec.affected_files_json), spec),"affected_modules": json.loads(rec.affected_modules_json),"tags": json.loads(rec.tags_json),"source": rec.source,- "evidence_file": rec.evidence_file,+ "evidence_file": evidence_file,"confidence": rec.confidence,"staleness_score": rec.staleness_score,"superseded_by": rec.superseded_by,@@ -117,6 +125,7 @@ async def update_decision_records(if repo == "all":return _unsupported_repo_all("update_decision_records")ctx = await _resolve_repo_context(repo)+ exclude_spec = _get_exclude_spec(ctx.path)if action not in _VALID_ACTIONS:return {@@ -155,7 +164,7 @@ async def update_decision_records(rec = await crud.get_decision(session, decision_id)if rec is None:return {"error": f"Decision {decision_id} not found"}- return {"action": "get", "decision": _serialize_decision(rec)}+ return {"action": "get", "decision": _serialize_decision(rec, exclude_spec)}# --- list ---if action == "list":@@ -175,7 +184,7 @@ async def update_decision_records(return {"action": "list","count": len(decisions),- "decisions": [_serialize_decision(d) for d in decisions],+ "decisions": [_serialize_decision(d, exclude_spec) for d in decisions],}# --- update ---diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex c702fe8d6..8a8a74ed6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -14,9 +14,12 @@ from repowise.core.persistence.models import (GraphNode,)from repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ filter_graph_nodes,+ is_excluded,)from repowise.core.registry import mcp_tool_registry as mcp@@ -37,6 +40,10 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)if repo == "all":return _unsupported_repo_all("get_dependency_path")ctx = await _resolve_repo_context(repo)+ exclude_spec = _get_exclude_spec(ctx.path)+ for _p in (source, target):+ if is_excluded(_p, exclude_spec):+ return {"error": f"'{_p}' is excluded by exclude_patterns."}async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)@@ -53,7 +60,7 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)GraphNode.repository_id == repository.id,))- nodes = node_result.scalars().all()+ nodes = filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)try:import networkx as nx@@ -64,8 +71,15 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)"explanation": "networkx not available for path queries",}+ # Build the graph only from surviving nodes/edges so shortest paths, common+ # ancestors, shared neighbors, and bridges never route through excluded files.+ allowed = {n.node_id for n in nodes} if exclude_spec else Nonegraph = nx.DiGraph()for e in edges:+ if allowed is not None and (+ e.source_node_id not in allowed or e.target_node_id not in allowed+ ):+ continuegraph.add_edge(e.source_node_id,e.target_node_id,diff --git a/packages/server/src/repowise/server/mcp_server/tool_diagram.py b/packages/server/src/repowise/server/mcp_server/tool_diagram.pyindex d30120eae..e3028d3f8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_diagram.py+++ b/packages/server/src/repowise/server/mcp_server/tool_diagram.py@@ -14,9 +14,11 @@ from repowise.core.persistence.models import (Page,)from repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ filter_graph_nodes,)from repowise.core.registry import mcp_tool_registry as mcp@@ -89,7 +91,7 @@ async def get_architecture_diagram(else GraphNode.repository_id == repository.id,))- nodes = result.scalars().all()+ nodes = filter_graph_nodes(list(result.scalars().all()), _get_exclude_spec(ctx.path))result = await session.execute(select(GraphEdge).where(@@ -100,8 +102,10 @@ async def get_architecture_diagram(node_ids = {n.node_id for n in nodes}pr_map = {n.node_id: n.pagerank for n in nodes}+ # Keep only edges whose BOTH endpoints survived exclude filtering — an+ # edge with one surviving endpoint would still render the excluded one.relevant_edges = sorted(- [e for e in edges if e.source_node_id in node_ids or e.target_node_id in node_ids],+ [e for e in edges if e.source_node_id in node_ids and e.target_node_id in node_ids],key=lambda e: pr_map.get(e.source_node_id, 0.0),reverse=True,)diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.pyindex 039b46a6e..a46694d04 100644--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py@@ -24,9 +24,12 @@ from repowise.server.mcp_server._graph_utils import (resolve_trace_communities,)from repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ filter_embedded_path_ids,+ is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -86,6 +89,14 @@ async def get_execution_flows(for n in top_nodes:entry_nodes.append((n, _ep_score(n)))+ exclude_spec = _get_exclude_spec(ctx.path)+ if exclude_spec:+ entry_nodes = [+ (n, s)+ for (n, s) in entry_nodes+ if not is_excluded(n.file_path or n.node_id, exclude_spec)+ ]+if not entry_nodes:return {"total_entry_points": 0,@@ -101,6 +112,10 @@ async def get_execution_flows(trace = await bfs_trace(session, repo_id, ep_node.node_id, max_depth, node_cache)+ # Drop excluded files reached downstream so they don't leak via the+ # trace (entry-point filtering above doesn't cover BFS descendants).+ if exclude_spec:+ trace = filter_embedded_path_ids(trace, exclude_spec)communities_visited, crosses = await resolve_trace_communities(session, repo_id, trace, node_cachediff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex e5bb89d0f..71fe1db33 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -16,7 +16,12 @@ from repowise.core.persistence.crud import ()from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import HealthFileMetric, HealthFinding-from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context+from repowise.server.mcp_server._helpers import (+ _get_exclude_spec,+ _get_repo,+ _resolve_repo_context,+ filter_rows_by_attr,+)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -165,7 +170,12 @@ async def get_health(all_metrics_q = select(HealthFileMetric).where(HealthFileMetric.repository_id == repository.id)- all_metrics = list((await session.execute(all_metrics_q)).scalars().all())+ exclude_spec = _get_exclude_spec(ctx.path)+ all_metrics = filter_rows_by_attr(+ list((await session.execute(all_metrics_q)).scalars().all()),+ "file_path",+ exclude_spec,+ )if module_targets:module_set = set(module_targets)@@ -192,14 +202,24 @@ async def get_health(if effective_targets:finding_q = finding_q.where(HealthFinding.file_path.in_(effective_targets))finding_q = finding_q.order_by(HealthFinding.health_impact.desc())- finding_rows = list((await session.execute(finding_q)).scalars().all())+ finding_rows = filter_rows_by_attr(+ list((await session.execute(finding_q)).scalars().all()),+ "file_path",+ exclude_spec,+ )coverage_rows: list[Any] = []coverage_summary: dict[str, Any] = {}if "coverage" in include_set:- coverage_rows = await load_coverage_for_repo(- session, repository.id, file_paths=list(targets) if targets else None+ coverage_rows = filter_rows_by_attr(+ await load_coverage_for_repo(+ session, repository.id, file_paths=list(targets) if targets else None+ ),+ "file_path",+ exclude_spec,)+ # coverage_summary is a repo-wide stored aggregate, not recomputed+ # here; the per-file rows above are exclude-filtered.coverage_summary = await get_coverage_summary(session, repository.id)snapshots: list[Any] = []diff --git a/packages/server/src/repowise/server/mcp_server/tool_metrics.py b/packages/server/src/repowise/server/mcp_server/tool_metrics.pyindex 96babcc35..999c34ef7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_metrics.py+++ b/packages/server/src/repowise/server/mcp_server/tool_metrics.py@@ -19,9 +19,11 @@ from repowise.core.persistence.crud import (from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNodefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -67,7 +69,8 @@ async def get_graph_metrics(# Try exact lookup firstnode = await get_graph_node(session, repo_id, target)- if node is None:+ node_path = node.node_id if node and node.node_type == "file" else getattr(node, "file_path", None)+ if node is None or is_excluded(node_path, _get_exclude_spec(ctx.path)):return {"target": target,"error": (diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 800f4d818..c96dc0a1c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -28,10 +28,13 @@ from repowise.core.persistence.models import ()from repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_is_workspace_mode,_resolve_all_contexts,_resolve_repo_context,+ filter_graph_nodes,+ filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -197,6 +200,7 @@ async def get_overview(repo: str | None = None) -> dict:return await _workspace_overview()ctx = await _resolve_repo_context(repo)+ exclude_spec = _get_exclude_spec(ctx.path)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)@@ -238,14 +242,17 @@ async def get_overview(repo: str | None = None) -> dict:GraphNode.is_test == False, # noqa: E712))- entry_nodes = [- n- for n in result.scalars().all()- if not any(- seg in n.node_id.lower()- for seg in ("fixture", "test_data", "testdata", "sample_repo")- )- ]+ entry_nodes = filter_graph_nodes(+ [+ n+ for n in result.scalars().all()+ if not any(+ seg in n.node_id.lower()+ for seg in ("fixture", "test_data", "testdata", "sample_repo")+ )+ ],+ exclude_spec,+ )# Phase 4: repo-wide git health summarygit_res = await session.execute(@@ -253,7 +260,9 @@ async def get_overview(repo: str | None = None) -> dict:GitMetadata.repository_id == repository.id,))- all_git = git_res.scalars().all()+ all_git = filter_rows_by_attr(+ list(git_res.scalars().all()), "file_path", exclude_spec+ )git_health: dict[str, Any] = {}if all_git:@@ -345,7 +354,7 @@ async def get_overview(repo: str | None = None) -> dict:GraphNode.node_type == "file",))- all_nodes = node_result.scalars().all()+ all_nodes = filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)else:node_result = await session.execute(select(GraphNode).where(@@ -353,7 +362,7 @@ async def get_overview(repo: str | None = None) -> dict:GraphNode.is_test == False, # noqa: E712))- all_nodes = node_result.scalars().all()+ all_nodes = filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)# Group file nodes by community_idcommunity_groups: dict[int, list[GraphNode]] = defaultdict(list)diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex dcef2411d..e2c79f858 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -21,10 +21,15 @@ from repowise.core.persistence.models import ()from repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_is_workspace_mode,_resolve_repo_context,_unsupported_repo_all,+ filter_dicts_by_key,+ filter_path_list,+ filter_rows_by_attr,+ is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -102,6 +107,7 @@ def _compute_impact_surface(target: str,reverse_deps: dict[str, set[str]],node_meta: dict[str, Any],+ exclude_spec: Any = None,) -> list[dict]:"""Find the top 3 most critical modules that depend on this file."""# BFS up to 2 hops through reverse dependencies@@ -131,6 +137,7 @@ def _compute_impact_surface(})ranked.sort(key=lambda x: -x["pagerank"])+ ranked = filter_dicts_by_key(ranked, "file_path", exclude_spec)return ranked[:3]@@ -197,6 +204,7 @@ async def _assess_one_target(import_links: dict[str, set[str]],reverse_deps: dict[str, set[str]],node_meta: dict[str, Any],+ exclude_spec: Any = None,) -> dict:"""Assess risk for a single target file.@@ -230,6 +238,7 @@ async def _assess_one_target(target,reverse_deps,node_meta,+ exclude_spec,)result_data["test_gap"] = await _check_test_gap(session, repo_id, target)result_data["security_signals"] = await _get_security_signals(session, repo_id, target)@@ -248,15 +257,19 @@ async def _assess_one_target(reverse=True,)[:5]import_related = import_links.get(target, set())- co_changes = [- {- "file_path": p.get("file_path", p.get("path", "")),- "count": p.get("co_change_count", p.get("count", 0)),- "last_co_change": p.get("last_co_change"),- "has_import_link": p.get("file_path", p.get("path", "")) in import_related,- }- for p in partners_sorted- ]+ co_changes = filter_dicts_by_key(+ [+ {+ "file_path": p.get("file_path", p.get("path", "")),+ "count": p.get("co_change_count", p.get("count", 0)),+ "last_co_change": p.get("last_co_change"),+ "has_import_link": p.get("file_path", p.get("path", "")) in import_related,+ }+ for p in partners_sorted+ ],+ "file_path",+ exclude_spec,+ )owner = meta.primary_owner_name or "unknown"pct = meta.primary_owner_commit_pct or 0.0@@ -268,7 +281,7 @@ async def _assess_one_target(risk_type = _classify_risk_type(meta, dep_count)# --- Impact surface ---- impact_surface = _compute_impact_surface(target, reverse_deps, node_meta)+ impact_surface = _compute_impact_surface(target, reverse_deps, node_meta, exclude_spec)# Phase 2: diff size & change magnitudelines_added = getattr(meta, "lines_added_90d", 0) or 0@@ -380,6 +393,10 @@ async def get_risk(if repo == "all":return _unsupported_repo_all("get_risk")ctx = await _resolve_repo_context(repo)+ exclude_spec = _get_exclude_spec(ctx.path)+ targets = filter_path_list(targets, exclude_spec)+ if changed_files:+ changed_files = filter_path_list(changed_files, exclude_spec)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)repo_id = repository.id@@ -417,6 +434,7 @@ async def get_risk(import_links,reverse_deps,node_meta,+ exclude_spec,)for t in targets]@@ -433,7 +451,9 @@ async def get_risk(.order_by(GitMetadata.churn_percentile.desc()).limit(len(targets) + 5))- all_hotspots = res.scalars().all()+ all_hotspots = filter_rows_by_attr(+ list(res.scalars().all()), "file_path", exclude_spec+ )global_hotspots = [{"file_path": h.file_path,@@ -580,10 +600,23 @@ async def get_risk(if len(partners) > 3:r["co_change_partners"] = partners[:3]+ def _as_path(entry: Any) -> str | None:+ if isinstance(entry, str):+ return entry+ if isinstance(entry, dict):+ return (+ entry.get("file_path")+ or entry.get("path")+ or entry.get("file")+ or entry.get("missing_partner")+ or entry.get("partner")+ )+ return None+# ``pr_blast_radius`` is the analyzer's own payload — preserve it for- # callers that want the full picture, but truncate the noisy lists so- # we stay well under the 25k-token transport ceiling on PRs that touch- # many files. The directive below is what the agent should read first.+ # callers that want the full picture, but drop excluded paths and+ # truncate the noisy lists so we stay well under the 25k-token transport+ # ceiling on PRs that touch many files.trimmed_blast: dict[str, Any] = dict(pr_blast_radius)for key, cap in (("transitive_affected", 15),@@ -592,7 +625,12 @@ async def get_risk(("recommended_reviewers", 5),):value = trimmed_blast.get(key)- if isinstance(value, list) and len(value) > cap:+ if not isinstance(value, list):+ continue+ if exclude_spec:+ value = [e for e in value if not is_excluded(_as_path(e), exclude_spec)]+ trimmed_blast[key] = value+ if len(value) > cap:trimmed_blast[key] = value[:cap]trimmed_blast[f"{key}_truncated_total"] = len(value)response["pr_blast_radius"] = trimmed_blast@@ -600,22 +638,19 @@ async def get_risk(# Directive: 3 short lists the agent can read in one glance. Each# entry is a file path (string), never a dossier. Designed to answer# "what should I do about this PR" in three lines.- def _as_path(entry: Any) -> str | None:- if isinstance(entry, str):- return entry- if isinstance(entry, dict):- return entry.get("file_path") or entry.get("path") or entry.get("file")- return None- will_break = [- p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", [])) if p- ][:5]- missing_cochanges = [- p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", [])) if p- ][:3]- missing_tests = [p for p in (_as_path(e) for e in trimmed_blast.get("test_gaps", [])) if p][- :3- ]+ will_break = filter_path_list(+ [p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", [])) if p],+ exclude_spec,+ )[:5]+ missing_cochanges = filter_path_list(+ [p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", [])) if p],+ exclude_spec,+ )[:3]+ missing_tests = filter_path_list(+ [p for p in (_as_path(e) for e in trimmed_blast.get("test_gaps", [])) if p],+ exclude_spec,+ )[:3]# Governance risk — bounded query over changed_files (small set).governance_risk: list[dict[str, Any]] = []diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex a2b56f749..b6ed5a1d4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -15,9 +15,11 @@ from repowise.core.persistence.models import ()from repowise.server.mcp_server import _statefrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_all_contexts,_resolve_repo_context,+ filter_dicts_by_key,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.core.registry import mcp_tool_registry as mcp@@ -257,6 +259,8 @@ async def search_codebase()git_map = {g.file_path: g for g in git_res.scalars().all()}+ output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))+for item in output:# Freshness boost: recently-active files rank highertarget_path = page_info.get(item["page_id"])diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 5afa0f85f..3ec5107a0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -38,9 +38,11 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import WikiSymbolfrom repowise.server.mcp_server._helpers import (+ _get_exclude_spec,_get_repo,_resolve_repo_context,_unsupported_repo_all,+ is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import symbol_hint as _symbol_hint@@ -319,7 +321,7 @@ async def get_symbol(repository = await _get_repo(session)row = await _resolve_symbol(session, repository.id, symbol_id)- if row is None:+ if row is None or is_excluded(getattr(row, "file_path", None), _get_exclude_spec(ctx.path)):return {"symbol_id": symbol_id,"error": (diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 503cc28af..49850e5af 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -20,11 +20,14 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._helpers import (_build_origin_story,_compute_alignment,+ _get_exclude_spec,_get_repo,_is_path,_resolve_all_contexts,_resolve_repo_context,_unsupported_repo_all,+ filter_path_list,+ is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_meta@@ -124,7 +127,9 @@ async def get_why("id": d.id,"title": d.title,"staleness_score": d.staleness_score,- "affected_files": json.loads(d.affected_files_json)[:5],+ "affected_files": filter_path_list(+ json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)+ )[:5],}for d in stale[:10]],@@ -145,6 +150,8 @@ async def get_why(# --- Mode 2: Path → decisions, origin story, alignment ---if _is_path(query):ctx = await _resolve_repo_context(repo)+ if is_excluded(query, _get_exclude_spec(ctx.path)):+ return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)res = await session.execute(diff --git a/tests/unit/server/mcp/test_mcp_exclude_filter.py b/tests/unit/server/mcp/test_mcp_exclude_filter.pynew file mode 100644index 000000000..1443d01dc--- /dev/null+++ b/tests/unit/server/mcp/test_mcp_exclude_filter.py@@ -0,0 +1,236 @@+"""Tests for per-repo exclude_patterns filtering helpers used by MCP tools (#296, issue 5)."""++from __future__ import annotations++from types import SimpleNamespace++import pathspec+import pytest++SPEC = pathspec.PathSpec.from_lines("gitwildmatch", [".claude/", "tools/"])+++# ---------------------------------------------------------------------------+# _get_exclude_spec / is_excluded+# ---------------------------------------------------------------------------+++def test_get_exclude_spec_loads_from_config(tmp_path):+ from repowise.server.mcp_server._helpers import _get_exclude_spec++ rw = tmp_path / ".repowise"+ rw.mkdir()+ (rw / "config.yaml").write_text(+ "exclude_patterns:\n - .claude/\n - tools/\n", encoding="utf-8"+ )++ spec = _get_exclude_spec(tmp_path)+ assert spec is not None+ assert spec.match_file(".claude/foo.py")+ assert spec.match_file("tools/build.sh")+ assert not spec.match_file("src/main.py")+++def test_get_exclude_spec_returns_none_when_no_patterns(tmp_path):+ from repowise.server.mcp_server._helpers import _get_exclude_spec++ rw = tmp_path / ".repowise"+ rw.mkdir()+ (rw / "config.yaml").write_text("embedder: minilm\n", encoding="utf-8")++ assert _get_exclude_spec(tmp_path) is None+++def test_is_excluded_checks_path():+ from repowise.server.mcp_server._helpers import is_excluded++ assert is_excluded(".claude/foo.py", SPEC) is True+ assert is_excluded("src/main.py", SPEC) is False+ assert is_excluded("src/main.py", None) is False+++# ---------------------------------------------------------------------------+# Shape A: ORM rows with a path attribute+# ---------------------------------------------------------------------------++[email protected]("attr", ["file_path", "node_id"])+def test_filter_rows_by_attr(attr):+ from repowise.server.mcp_server._helpers import filter_rows_by_attr++ keep = SimpleNamespace(**{attr: "src/main.py"})+ drop = SimpleNamespace(**{attr: ".claude/x.py"})+ drop2 = SimpleNamespace(**{attr: "tools/build.sh"})++ assert filter_rows_by_attr([keep, drop, drop2], attr, SPEC) == [keep]+ assert filter_rows_by_attr([keep, drop], attr, None) == [keep, drop]+++# ---------------------------------------------------------------------------+# Shape B: GraphNode file nodes (node_id) vs symbol nodes (file_path)+# ---------------------------------------------------------------------------+++def test_filter_graph_nodes_uses_node_id_for_file_nodes():+ from repowise.server.mcp_server._helpers import filter_graph_nodes++ file_keep = SimpleNamespace(node_type="file", node_id="src/main.py", file_path=None)+ file_drop = SimpleNamespace(node_type="file", node_id=".claude/c.py", file_path=None)+ sym_keep = SimpleNamespace(node_type="symbol", node_id="src/main.py::foo", file_path="src/main.py")+ sym_drop = SimpleNamespace(node_type="symbol", node_id=".claude/c.py::bar", file_path=".claude/c.py")++ result = filter_graph_nodes([file_keep, file_drop, sym_keep, sym_drop], SPEC)+ assert result == [file_keep, sym_keep]+ assert filter_graph_nodes([file_drop], None) == [file_drop]+++# ---------------------------------------------------------------------------+# Shape C: result dicts with a path key+# ---------------------------------------------------------------------------++[email protected]("key", ["target_path", "file_path", "file"])+def test_filter_dicts_by_key(key):+ from repowise.server.mcp_server._helpers import filter_dicts_by_key++ keep = {key: "src/main.py", "v": 1}+ drop = {key: ".claude/c.py", "v": 2}++ assert filter_dicts_by_key([keep, drop], key, SPEC) == [keep]+ assert filter_dicts_by_key([keep, drop], key, None) == [keep, drop]+++# ---------------------------------------------------------------------------+# Shape D: nested path-list of strings+# ---------------------------------------------------------------------------+++def test_filter_path_list():+ from repowise.server.mcp_server._helpers import filter_path_list++ assert filter_path_list(["src/a.py", ".claude/c.py", "tools/b.sh"], SPEC) == ["src/a.py"]+ assert filter_path_list(["src/a.py", ".claude/c.py"], None) == ["src/a.py", ".claude/c.py"]+ assert filter_path_list(None, SPEC) == []+++# ---------------------------------------------------------------------------+# Shape E: node IDs that embed a path ("path::Name")+# ---------------------------------------------------------------------------+++def test_filter_embedded_path_ids():+ from repowise.server.mcp_server._helpers import filter_embedded_path_ids++ ids = ["src/main.py::foo", ".claude/c.py::bar", "tools/b.sh::baz"]+ assert filter_embedded_path_ids(ids, SPEC) == ["src/main.py::foo"]+ assert filter_embedded_path_ids(ids, None) == ids+++# ---------------------------------------------------------------------------+# End-to-end: a real tool honors exclude_patterns from repo config+# ---------------------------------------------------------------------------+++async def test_get_health_excludes_configured_paths(setup_mcp, health_data, tmp_path, monkeypatch):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_health++ rw = tmp_path / ".repowise"+ rw.mkdir()+ (rw / "config.yaml").write_text("exclude_patterns:\n - src/db/\n", encoding="utf-8")+ monkeypatch.setattr(mcp_mod._state, "_repo_path", str(tmp_path))++ result = await get_health()+ paths = {m["file_path"] for m in result.get("worst_files", [])}+ assert "src/db/models.py" not in paths+ assert "src/auth/service.py" in paths+++# ---------------------------------------------------------------------------+# Targeted traversal-leak tests (edges / paths / co-change), not just helpers+# ---------------------------------------------------------------------------+++def _set_excluded(monkeypatch, tmp_path, pattern: str) -> None:+ import repowise.server.mcp_server as mcp_mod++ rw = tmp_path / ".repowise"+ rw.mkdir()+ (rw / "config.yaml").write_text(f"exclude_patterns:\n - {pattern}\n", encoding="utf-8")+ monkeypatch.setattr(mcp_mod._state, "_repo_path", str(tmp_path))+++async def test_diagram_excludes_node_and_its_edges(setup_mcp, tmp_path, monkeypatch):+ """An excluded endpoint must not render even though it has a surviving+ neighbor (service.py -> models.py edge)."""+ from repowise.server.mcp_server.tool_diagram import get_architecture_diagram++ _set_excluded(monkeypatch, tmp_path, "src/db/")+ # scope="module" forces the graph-computed path (scope="repo" returns a+ # stored page that bypasses node/edge filtering).+ result = await get_architecture_diagram(scope="module")+ mermaid = result["mermaid_syntax"]+ assert "src_db_models_py" not in mermaid # excluded endpoint not rendered+ assert "src_auth_service_py" in mermaid # non-excluded node still present+++async def test_dependency_path_excludes_intermediate(setup_mcp, tmp_path, monkeypatch):+ """middleware.py -> models.py only routes through service.py; excluding+ service.py must not surface it as an intermediate."""+ import json++ from repowise.server.mcp_server.tool_dependency import get_dependency_path++ _set_excluded(monkeypatch, tmp_path, "src/auth/service.py")+ result = await get_dependency_path("src/auth/middleware.py", "src/db/models.py")+ assert "src/auth/service.py" not in json.dumps(result)+++async def test_risk_co_change_partners_exclude_filtered(setup_mcp, tmp_path, monkeypatch):+ """service.py's co-change partners include models.py; excluding src/db/+ must drop it from co_change_partners."""+ from repowise.server.mcp_server import get_risk++ _set_excluded(monkeypatch, tmp_path, "src/db/")+ result = await get_risk(["src/auth/service.py"])+ target = result["targets"]["src/auth/service.py"]+ partner_paths = {p["file_path"] for p in target.get("co_change_partners", [])}+ assert "src/db/models.py" not in partner_paths+++async def test_flows_trace_excludes_downstream(setup_mcp, tmp_path, monkeypatch):+ """A non-excluded entry can reach excluded files downstream; those must not+ appear in any trace."""+ import json++ from repowise.server.mcp_server.tool_flows import get_execution_flows++ _set_excluded(monkeypatch, tmp_path, "src/db/")+ result = await get_execution_flows()+ assert "src/db/models.py" not in json.dumps(result.get("flows", []))+++async def test_risk_raw_pr_blast_radius_excludes_filtered(setup_mcp, tmp_path, monkeypatch):+ """The raw pr_blast_radius payload (not just the directive lists) must not+ carry excluded paths."""+ import json++ from repowise.server.mcp_server import get_risk++ args = (["src/auth/service.py"],)+ kwargs = {"changed_files": ["src/auth/service.py"]}++ # Baseline (no exclude config) — confirm the path is present, so the test+ # below is not vacuous.+ baseline = await get_risk(*args, **kwargs)+ assert "src/db/models.py" in json.dumps(baseline.get("pr_blast_radius", {}))++ _set_excluded(monkeypatch, tmp_path, "src/db/")+ result = await get_risk(*args, **kwargs)+ assert "src/db/models.py" not in json.dumps(result.get("pr_blast_radius", {}))