"""MCP server exposing the index as tools. Runs over stdio, so nothing here may write to stdout — that stream carries the JSON-RPC protocol. The embedding server is started lazily on the first search rather than at startup, because loading the model takes long enough to trip a client's connection timeout. """ from __future__ import annotations import os from mcp.server import MCPServer from . import embed from .store import Store # A chunk is ~320 tokens; this keeps a full result set readable without flooding # the caller's context. MAX_LINES_PER_HIT = 60 MAX_CHARS_PER_HIT = 2400 server = MCPServer( name="code-index", version="0.1.0", instructions=( "Semantic search over the source repositories indexed on this machine. " "Use search_code when you know what something does but not what it is called " "— it matches on meaning, so a description of behaviour finds the code even " "when the identifiers differ. Use grep instead when you know the exact string. " "The index spans every repository at once, so results may come from a " "repository other than the one being worked on; pass `repo` to narrow." ), ) def _truncate(text: str) -> str: lines = text.split("\n") if len(lines) > MAX_LINES_PER_HIT: dropped = len(lines) - MAX_LINES_PER_HIT lines = lines[:MAX_LINES_PER_HIT] + [f"... ({dropped} more lines)"] out = "\n".join(lines) if len(out) > MAX_CHARS_PER_HIT: out = out[:MAX_CHARS_PER_HIT] + "\n... (truncated)" return out @server.tool( description=( "Search local source repositories by meaning rather than exact text. " "Phrase the query as a description of what the code does — 'where stale " "sessions get expired', 'retry backoff for failed uploads' — not as a " "keyword. Returns ranked chunks with repository, path, and line range." ) ) def search_code( query: str, limit: int = 8, repo: str | None = None, path: str | None = None, paths_only: bool = False, ) -> str: """Search the code index. Args: query: What the code does, in plain language. limit: Number of results (1-30). repo: Restrict to one repository by its directory name. path: Restrict to paths containing this substring, e.g. "renderer/". paths_only: Return locations and scores without source text. """ limit = max(1, min(int(limit), 30)) store = Store(dim=embed.EMBED_DIM) if store.vector_count() == 0: return "The index is empty. Build it with: code-index index" embed.start() vec = embed.embed([query], is_query=True)[0] hits = store.search(vec, k=limit, repo=repo, path_filter=path) if not hits: scope = [] if repo: scope.append(f"repo={repo}") if path: scope.append(f"path={path}") suffix = f" within {', '.join(scope)}" if scope else "" return f"No matches for {query!r}{suffix}." blocks = [] for hit in hits: name = os.path.basename(hit.repo) header = ( f"{name}/{hit.rel}:{hit.start_line}-{hit.end_line} (score {hit.score:.3f})" ) if paths_only: blocks.append(header) else: blocks.append(f"{header}\n{_truncate(hit.text)}") joined = "\n\n".join(blocks) return f"{len(hits)} result(s) for {query!r}:\n\n{joined}" @server.tool( description=( "Report what the code index covers, when it was last built, and whether the " "embedding server is running. Call this if a search returns nothing to check " "whether the repository in question is indexed at all." ) ) def index_status() -> str: """Show index coverage and freshness.""" store = Store(dim=embed.EMBED_DIM) st = store.stats() if not st["repos"]: return "The index is empty. Build it with: code-index index" lines = [ f"model: {st['model'] or '-'}", f"built: {st['built_at'] or '-'}", f"files: {st['files']}", f"chunks: {st['chunks']}", f"server: {'running' if embed.is_up() else 'stopped (starts on first search)'}", "", "repositories indexed:", ] for repo_path, n in st["repos"]: lines.append(f" {os.path.basename(repo_path):24} {n:5d} files") return "\n".join(lines) def main() -> None: server.run("stdio") if __name__ == "__main__": main()